mongoose – MissingSchema错误的人口
我有两个mongoose模型:
1-事件模型:
eventSchema = new mongoose.Schema({ name: { type: String, required: true, }, location: { type: { type: String, default: 'Point', required: true }, coordinates: { type: [Number], required: true }, }, sport: { type: mongoose.Schema.Types.ObjectId, ref: 'Sport', required: true, }, startDate: { type: Date, required: true, }, description: { type: String, required: true, }, host: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true, }, players: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User', }], }, { timestamps: true });
2-用户型号:
userSchema = new mongoose.Schema({ email: { type: String, required: true, unique: true, }, password: { type: String, required: true, }, firstName: { type: String, required: true, }, lastName: { type: String, required: true, }, age: { type: Number, required: true, }, location: { type: String, }, }, { timestamps: true });
在我的EventService
我试图通过idfind一个事件,并返回sport
host
和players
填充的字段。 前两个字段在填充时不会产生任何错误,并且工作正常,但是问题在于players
字段。 它会抛出这个错误:
{ MissingSchemaError: Schema hasn't been registered for model "players". Use mongoose.model(name, schema) at MissingSchemaError (/Users/elias/Documents/tfg/sporter-app/sporter-api/node_modules/mongoose/lib/error/missingSchema.js:20:11) at NativeConnection.Connection.model (/Users/elias/Documents/tfg/sporter-app/sporter-api/node_modules/mongoose/lib/connection.js:1043:11) at getModelsMapForPopulate (/Users/elias/Documents/tfg/sporter-app/sporter-api/node_modules/mongoose/lib/model.js:3569:20) at populate (/Users/elias/Documents/tfg/sporter-app/sporter-api/node_modules/mongoose/lib/model.js:3113:15) at _populate (/Users/elias/Documents/tfg/sporter-app/sporter-api/node_modules/mongoose/lib/model.js:3081:5) at Function.Model.populate (/Users/elias/Documents/tfg/sporter-app/sporter-api/node_modules/mongoose/lib/model.js:3041:5) at Immediate.<anonymous> (/Users/elias/Documents/tfg/sporter-app/sporter-api/node_modules/mongoose/lib/query.js:1441:17) at Immediate.<anonymous> (/Users/elias/Documents/tfg/sporter-app/sporter-api/node_modules/mquery/lib/utils.js:137:16) at runCallback (timers.js:781:20) at tryOnImmediate (timers.js:743:5) at processImmediate [as _immediateCallback] (timers.js:714:5) message: 'Schema hasn\'t been registered for model "players".\nUse mongoose.model(name, schema)', name: 'MissingSchemaError' }
最后这就是我如何调用.populate()
方法:
const event = await Event.findById(eventId) .populate('sport', 'host', 'players') .exec();
有什么想法我做错了什么? 谢谢!
尝试这个:
const event = await Event.findById(eventId) .populate('sport') .populate('host') .populate('players') .exec()
这里有一节在文档中填充多个path : http : //mongoosejs.com/docs/populate.html
在使用mongoose.model('name',schema)之前,您需要使用mongoose.model('name',schema)来创build所有模型,因为它会在mongoose.models键/值上find需要在为该密钥运行时使用的模型。
因此,加载模型+连接,然后使用任何这些模型。