mongoose嵌套/深填充

我知道这个问题已经被问了很多次,但是我对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填充 :我如何实现一个嵌套mongoose填充Appointments.find()的方式,Appointments.find()。填充('doctorids')应该填充的医生数组,而医生数组应该填充每个医生指出的用户。 按照https://github.com/LearnBoost/mongoose/wiki/3.6-Release-Notes#population他们添加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://stackoverflow.com/questions/27412928/mongoose-nested-populate-sort-search-referenced-attributes ]

有很多问题,我只想解决深人口问题(第一个问题)。 (另外,我build议你把问题分解成多个,以防人们对一个问题有答案,但不是全部。)

虽然Mongoose支持嵌套人口,但您必须手动调用每个模型上的填充以在每个嵌套级别填充。 另外,你可以使用mongoose深度填充插件来做到这一点(免责声明:我是该插件的作者)。 例如,你可以写这个来填充医生和用户:

 Apartments.find({}, function (err, apts) { Apartments.deepPopulate(docs, 'doctorids.userid', function (err, apts) { // now every `apt` instance has doctors and user }) }) 

您还可以指定Mongoose填充选项来控制每个填充path的sorting顺序,如下所示:

 var options = { doctorids: { options: { sort: '-name' } } } Apartments.deepPopulate(docs, 'doctorids.userid', options, cb) 

查看插件文档以获取更多信息。