Mongo Schemas - Mocha测试时出现Mongoose错误(MissingSchemaError和OverwriteModelError)

时间:2018-01-16 18:27:24

标签: mongodb express mocha mongoose-schema

编辑 - 看来我这里有两个问题。我接受了下面给出的答案,但请阅读评论,因为mocha -w问题在修复中同样重要。

我已经阅读了一些SO问题和答案,并尝试了一些建议的方法,但我仍然无法解决这个问题所以我希望有人可以帮助我:

我有一个模特:

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const slug = require('slugs');

const storySchema = new mongoose.Schema({
  name :{
    type: String,
    trim: true,
    required: 'Please enter a store name'
},
  slug: String,
  storyText: {
    type: String,
    trim:true
},
  keyStageLevel: [String]
});


module.exports = mongoose.model('Story', storySchema);

和storyController:

const mongoose = require('mongoose');
const Story = mongoose.model('Story');

exports.storyHomePage = (req, res) => {
console.log(req.name);
res.render('story', {
    title:"Reading Project = Story Home Page",
    created:req.query.created

  });
};

我有摩卡运行一些测试。但是当我运行测试时出现错误

MissingSchemaError: Schema hasn't been registered for model "Store".

阅读此https://stackoverflow.com/a/21915511/1699434我可以将我的storyController修改为

const mongoose = require('mongoose');

mongoose.model('Story', new mongoose.Schema());

const Story = mongoose.model('Story')

让Mocha保持高兴但是nodemon却出现了错误

OverwriteModelError: Cannot overwrite故事model once compiled.

环顾这个https://stackoverflow.com/a/19051909/1699434似乎可以回答这个问题,但据我所知,我正在使用这种方法(我使用const Store = mongoose.model('Store');代替const Store = require('../models/Store')

所以我有点卡住了。任何帮助非常感谢!

编辑以包含start.js

const mongoose = require('mongoose');


// import environmental variables from our variables.env file
require('dotenv').config({ path: 'variables.env' });

// Connect to our Database and handle any bad connections
mongoose.connect(process.env.DATABASE);
mongoose.Promise = global.Promise; // Tell Mongoose to use ES6 promises
mongoose.connection.on('error', (err) => {
  console.error(`${err.message}`);
});

//import all of the models
require('./models/Story');

// Start app
const app = require('./app');
app.set('port', process.env.PORT || 7777);
const server = app.listen(app.get('port'), () => {
console.log(`Express running → PORT ${server.address().port}`);
});

1 个答案:

答案 0 :(得分:0)

您应该使用以下语法导入Story模型,并且无需再次导入mongoose模块:

// I suppose the file is located in 'models' folder and the current folder is 'controllers'
const Story = require('../models/story');

通过执行const Story = mongoose.model('Story');,您创建的是没有架构定义的Story模型,这就是您获得Schema hasn't been registered for model "Store".

的原因

在你的第二个例子中:

// this create a new model from an empty schema (schema without fields)
mongoose.model('Story', new mongoose.Schema());

// overwriting the first model which is not allowed by mongoose
const Story = mongoose.model('Story')

请记住,mongoose.model()方法仅定义映射到MongoDB集合的模式中的模型