簡體   English   中英

Mongoose嵌套/深填充

[英]Mongoose nested/deep populate

我知道很多次都會問這個問題,但我對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()上實現一個嵌套的mongoose populate,其方式是Appointments.find()。populate('doctorids')應該填充Doctors數組,而醫生的數組依次填充每個博士指向的用戶。 根據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 ]

有很多問題,我將只解決人口密集的問題(第一個問題)。 (另外,我建議你將問題分成多個問題,以防人們得到答案但不是全部。)

雖然貓鼬支持嵌套的人口,你必須手動調用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選項來控制每個填充路徑的排序順序,如下所示:

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

查看插件文檔以獲取更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM