MissingSchemaError:架构尚未注册模型

我有一个Node.js – Express 3 – MongoDB的典型项目

我试图在我的/routes/index.js中对我的模型“Tweet”进行查询,当我运行我的应用程序时崩溃

24 Aug 11:35:07 - [nodemon] starting `node app.js` /Applications/XAMPP/xamppfiles/htdocs/ocesa/fanocesa/node_modules/mongoose/lib/index.js:286 throw new mongoose.Error.MissingSchemaError(name); ^ MissingSchemaError: Schema hasn't been registered for model "Teewt". Use mongoose.model(name, schema) at Mongoose.model (/Applications/XAMPP/xamppfiles/htdocs/ocesa/fanocesa/node_modules/mongoose/lib/index.js:286:13) at Object.<anonymous> (/Applications/XAMPP/xamppfiles/htdocs/ocesa/fanocesa/routes/index.js:6:33) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Module.require (module.js:364:17) at require (module.js:380:17) at Object.<anonymous> (/Applications/XAMPP/xamppfiles/htdocs/ocesa/fanocesa/app.js:7:14) at Module._compile (module.js:456:26) 24 Aug 11:35:07 - [nodemon] app crashed - waiting for file changes before starting... 

这是我的app.js的一部分

 var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/fanOcesa'); var Schema = mongoose.Schema; var ObjectID = Schema.ObjectID; var Teewt = new Schema({ cuerpo: String }); var Teewt = mongoose.model('Teewt', Teewt); var app = express(); app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } app.get('/', routes.index); app.get('/users', user.list); 

这是我的index.js的一部分

 var Teewt = require('mongoose').model('Teewt'); Teewt.find({}, function(err, docs){ console.log('docs'); console.log(docs); }); exports.index = function(req, res){ res.render('index', { docs: docs }); }; 

这将是做这个查询的正确方法?

index.js文件在app.js文件调用的地方执行:

 var routes = require('./routes'); 

所以要确保你的调用之后调用'Teewt'模式作为app.js 'Teewt'模型。

命名您的模式和模型不同。 重新声明Teewt是一个JavaScript“不好的部分”,也是任何编程语言的错误。 只需调用模式TeewtSchemaTeewtSchema模型(因为模式通常只在一个应用程序中的一个文件中使用,但是模型可能被广泛使用)。

我也有这个错误。 被困惑了很长时间,以下和类似的线程寻求帮助,试图debugging。 最终问题原来是由于我的情况下mongoose版本。 我正在尝试使用mongoose灯具种子一些默认的数据开始到mongo。

试试这个:删除你的项目的node_modules目录,运行一个npm cache clean ,然后一个npm install 。 如果即使这样也没有帮助,请尝试比较有问题的应用程序和工作的应用程序之间的mongoose / mongoose-fixture版本,然后尝试更改package.json的版本,然后重复上述步骤。 这对我有效。

换句话说,这行(来自app.js):

 var Teewt = mongoose.model('Teewt', Teewt); 

应该在Tweet注册之后调用(在index.js中):

 var Teewt = require('mongoose').model('Teewt');