MissingSchemaError:架构没有'尚未注册型号

MissingSchemaError: Schema hasn't been registered for model

本文关键字:注册型 MissingSchemaError      更新时间:2023-09-26

我有一个典型的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');

因此,请确保在调用之后调用,以便在app.js中将'Teewt'模式注册为猫鼬模型。

以不同的方式命名模式和模型。重新声明Teewt是javascript的"坏部分",在任何编程语言中都是错误的。只需调用模式TeewtSchema和模型Teewt(因为模式通常只在应用程序中的一个文件中使用,但模型可能会被广泛使用)。

我也收到了这个错误。困惑了很长时间,跟随这个和类似的线程寻求帮助,试图调试。最终,这个问题是由于猫鼬版本在我的情况下。我试图使用mongoose fixture将一些默认数据播种到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');