我有Patient
个模型,其中包含对Path
的引用:
const PatientSchema = Schema({
idPatient: Schema.Types.ObjectId,
firstName: String,
lastName: String,
path: {type: Schema.Types.ObjectId, ref: 'Path'}
});
Path
模型,其中包含对Zone
的引用数组:
const PathSchema = connection.mongoose.Schema({
zones: [{
type: connection.mongoose.Schema.Types.ObjectId,
ref: 'Zone'
}],
});
最后是Zone
模型:
const ZoneSchema = connection.mongoose.Schema({
name: String,
duration: Number,
});
我正在尝试让所有患者了解其路径以及患者内部每个路径的区域:
下面是在患者身上进行简单填充的数据示例:
[
{
"_id": "5d00b7dab927301ad392e6e4",
"idPatient": "5d00b7dab927301ad392e6e5",
"firstName": "Amine",
"lastName": "Harbaoui",
"path": {
"_id": "5d010263b927301ad392e6ea",
"zones": [
"5d010c72b927301ad392e6eb",
"5d010cf7b927301ad392e6ec"
]
}
}
]
这里是我如何获得想要的东西:
Patient.find()
.lean()
.populate('path')
.exec((error, patients) => {
if (error) {
console.log(error);
} else {
const zones = patients.map(p => p.path.zones);
Path.populate(zones, {
path: 'zones'
}, (error, data) => {
if (error) {
console.log(error);
} else {
console.log(data);
}
})
}
})
但这是我得到的例外:
{MissingSchemaError:尚未为模型“ Zone”注册架构。 使用mongoose.model(名称,模式) 在新的MissingSchemaError(/home/amine/ubudu/app_mn/sprint0/server/node_modules/mongoose/lib/error/missingSchema.js:22:11) 在NativeConnection.Connection.model(/home/amine/ubudu/app_mn/sprint0/server/node_modules/mongoose/lib/connection.js:888:11) 在getModelsMapForPopulate(/home/amine/ubudu/app_mn/sprint0/server/node_modules/mongoose/lib/model.js:4337:57) 在填充(/home/amine/ubudu/app_mn/sprint0/server/node_modules/mongoose/lib/model.js:3915:21) 在_populate(/home/amine/ubudu/app_mn/sprint0/server/node_modules/mongoose/lib/model.js:3885:5) 在utils.promiseOrCallback.cb(/home/amine/ubudu/app_mn/sprint0/server/node_modules/mongoose/lib/model.js:3858:5) 在Object.promiseOrCallback(/home/amine/ubudu/app_mn/sprint0/server/node_modules/mongoose/lib/utils.js:248:12) 在Function.Model.populate(/home/amine/ubudu/app_mn/sprint0/server/node_modules/mongoose/lib/model.js:3857:16) 在Patient.find.lean.populate.exec(/ home / amine / ubudu / app_mn / sprint0 / server / controllers / PatientController.js:61:14) 在/home/amine/ubudu/app_mn/sprint0/server/node_modules/mongoose/lib/model.js:4733:16 在/home/amine/ubudu/app_mn/sprint0/server/node_modules/mongoose/lib/utils.js:263:16 在_hooks.execPost(/home/amine/ubudu/app_mn/sprint0/server/node_modules/mongoose/lib/query.js:4224:11) 在/home/amine/ubudu/app_mn/sprint0/server/node_modules/kareem/index.js:135:16 在process._tickCallback(internal / process / next_tick.js:61:11)消息中:“尚未为模型“区域”注册架构。\ n使用 mongoose.model(name,schema)',名称:'MissingSchemaError'}
答案 0 :(得分:0)
只要您使用的是猫鼬的最新版本,就可以在一个查询中填充深度嵌套的值。
Patient.find()
.populate({
path: 'path',
populate: {
path: 'zones'
}
}).exec()