首页 文章

Mongoose嵌套/深填充

提问于
浏览
1

我知道很多次都会问这个问题,但我对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);

Nested Mongoose Populate :我如何在Appointments.find()上实现嵌套的mongoose populate,其方式是Appointments.find() . populate('doctorids')应该填充Doctors数组,而医生数组依次填充Users每个Doctor点数至 . 根据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]

1 回答

  • 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以获取更多信息 .

相关问题