Mongoose Schema尚未注册模型
我正在学习平均堆栈,当我尝试启动服务器使用
npm start
我得到一个exception说:
schema hasn't been registered for model 'Post'. Use mongoose.model(name, schema)
这里是我的代码/models/Posts.js
var mongoose = require('mongoose'); var PostSchema = new mongoose.Schema({ title: String, link: String, upvotes: { type: Number, default: 0 }, comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }] }); mongoose.model('Post', PostSchema);
因为我可以看到模式应该注册为模型'Post',但是可能导致exception被抛出的原因是什么?
提前致谢。
编辑:这是exception错误
/home/arash/Documents/projects/personal/flapper-news/node_modules/mongoose/lib/index.js:323 throw new mongoose.Error.MissingSchemaError(name); ^ MissingSchemaError: Schema hasn't been registered for model "Post". Use mongoose.model(name, schema)
这里是与mongoose初始化的app.js代码:
var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/news'); require('./models/Posts'); require('./models/Comments');
行前:
app.use('/', routes);
这不是模型导出的问题。 我遇到过同样的问题。
真正的问题是需要模型的陈述
var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/news'); require('./models/Posts'); require('./models/Comments');
低于路线依赖。 只需将mongoDB依赖项移动到路由依赖关系之上即可。 这应该是这样的:
// MongoDB var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/news'); require('./models/Posts'); require('./models/Comments'); var routes = require('./routes/index'); var users = require('./routes/users'); var app = express();
如果有人用正确答案的方法来解决问题(比如我),试着看看架构的创build。 我把'ref'写成'User',但是正确的是'user'。
错误:
createdBy: { type: Schema.Types.ObjectId, ref: 'User' }
正确:
createdBy: { type: Schema.Types.ObjectId, ref: 'user' }
在上面Rafael Grilli的回答中,
正确:
var HouseSchema = new mongoose.Schema({ date: {type: Date, default:Date.now}, floorplan: String, name:String, house_id:String, addressLine1:String, addressLine2:String, city:String, postCode:String, _locks:[{type: Schema.Types.ObjectId, ref: 'xxx'}] //ref here refers to the first parameter passed into mongoose.model() }); var House = mongoose.model('xxx', HouseSchema, 'houseschemas');
如果您使用多个mongoDB连接
当使用.populate()时,你必须提供模型,mongoose只会在相同的连接上“查找”模型。 即其中:
var db1 = mongoose.createConnection('mongodb://localhost:27017/gh3639'); var db2 = mongoose.createConnection('mongodb://localhost:27017/gh3639_2'); var userSchema = mongoose.Schema({ "name": String, "email": String }); var customerSchema = mongoose.Schema({ "name" : { type: String }, "email" : [ String ], "created_by" : { type: mongoose.Schema.Types.ObjectId, ref: 'users' }, }); var User = db1.model('users', userSchema); var Customer = db2.model('customers', customerSchema);
正确:
Customer.findOne({}).populate('created_by', 'name email', User)
要么
Customer.findOne({}).populate({ path: 'created_by', model: User })
不正确 (产生“架构尚未注册模型”错误):
Customer.findOne({}).populate('created_by');