Mongoose MissingSchemaError与Mocha测试不一致

时间:2015-08-22 17:49:08

标签: javascript node.js mongodb mongoose

users.spec.js我有这个,它运作良好:

var mongoose = require('mongoose');
var assert = require('assert');
var request = require('supertest');
var app = require('../../app.js');
var User = mongoose.model('User');
var Local = mongoose.model('Local');
var agent = request.agent(app);
var invalidId = 'aaaaaaaaaaaaaaaaaaaaaaaa';

app.js我有:

mongoose.connect(dbUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'Problem connecting to database.'));
db.once('open', function onDbConnect() {
  console.log('Connected to ' + dbUrl + ' database...');
  // create models
  require('./api/users/user.model.js');

user.model.js我有:

var User = mongoose.model('User', userSchema);
var Local = mongoose.model('Local', localSchema);

因此,当users.spec.js运行时,它首先创建模型,然后我可以通过mongoose.model('User')mongoose.model('Local')引用它们。

然而,在auth.spec.js中,我做同样的事情,并且它无法正常工作:

var mongoose = require('mongoose');
var assert = require('assert');
var request = require('supertest');
var app = require('../../app.js');
var User = mongoose.model('User');
var Local = mongoose.model('Local');
var agent = request.agent(app);

输出:

/Users/azerner/code/mean-starter/node_modules/mongoose/lib/index.js:332
      throw new mongoose.Error.MissingSchemaError(name);
            ^
MissingSchemaError: Schema hasn't been registered for model "User".
Use mongoose.model(name, schema)
    at Mongoose.model (/Users/azerner/code/mean-starter/node_modules/mongoose/lib/index.js:332:13)
    at Object.<anonymous> (/Users/azerner/code/mean-starter/server/api/auth/auth.spec.js:5:21)

这是为什么?我分开运行测试:mocha server/api/authmocha server/api/users,所以他们不应该互相干扰。

完整代码here

注意:这有效,但我不想使用它。或者至少我想了解问题是什么以及为什么会这样。

// :( https://github.com/Automattic/mongoose/issues/1251
// it isn't exactly my issue, but the recommendation on the bottom works
try {
  var User = mongoose.model('User');
  var Local = mongoose.model('Local');
}
catch(e) { 
  var schemas = require('../users/user.model.js');
  var User = mongoose.model('User', schemas.UserSchema);
  var Local = mongoose.model('Local', schemas.LocalSchema);
}

0 个答案:

没有答案