我知道很多次都会问这个问题,但我对mongodb / mongoose有点新鲜!目前我正在研究用于医疗软件的MEAN堆栈。以下是我的架构:
var usersSchema = new Schema({
_id : {type : mongoose.Schema.ObjectId}
//...
});
mongoose.model('Users', usersSchema);
var doctorsSchema = new Schema({
_id : {type : mongoose.Schema.ObjectId},
userid : {type : mongoose.Schema.ObjectId, ref : 'Users' },
//...
});
mongoose.model('Doctors', doctorsSchema);
var appointmentsSchema = new Schema({
_id : {type : mongoose.Schema.ObjectId},
doctorids : [ {type : mongoose.Schema.ObjectId, ref : 'Doctors'} ]
//...
});
mongoose.model('Appointments', appointmentsSchema);
嵌套的Mongoose Populate :我如何以Appointments.find()。populate('doctorids')填充医生数组的方式在Appointments.find()上实现嵌套的mongoose填充然后医生阵列应该填充每个医生指向的用户。根据{{3}},他们添加了Model.Populate!所以我尝试了这个,但它没有填充在doctorids中的用户
Appointments
.find({})
.populate('doctorids') // This is working
.exec(function (err, doc) {
if (err) {
handleError(err);
return;
}
Doctors //**Shouldn't this populate the doctors Users inside Doctors?**
.populate(doc, {path: 'doctorids.userid'}, function(err, doc) {
});
res.json({
appointments: doc //Appointsments.Doctorids[].Userid is NOT populated
});
});
[编辑:将其他问题移至https://github.com/LearnBoost/mongoose/wiki/3.6-Release-Notes#population的新帖子
答案 0 :(得分:3)
有很多问题,我将只解决人口密集的问题(第一个问题)。 (另外,我建议你将问题分成多个问题,以防人们得到答案但不是全部。)
虽然Mongoose支持嵌套填充,但您必须在每个模型上手动调用populate
以在每个嵌套级别填充。或者,您可以使用mongoose-deep-populate插件执行此操作(免责声明:我是该插件的作者)。例如,您可以将其写入以填充医生和用户:
Apartments.find({}, function (err, apts) {
Apartments.deepPopulate(docs, 'doctorids.userid', function (err, apts) {
// now every `apt` instance has doctors and user
})
})
您还可以指定Mongoose populate options来控制每个填充路径的排序顺序,如下所示:
var options = {
doctorids: {
options: {
sort: '-name'
}
}
}
Apartments.deepPopulate(docs, 'doctorids.userid', options, cb)
查看插件documentation以获取更多信息。