如何使用Mongoose查找子文档?

时间:2018-08-03 08:41:25

标签: node.js database mongodb mongoose

我有mongodb数据库,并使用mongoose

它是由以下模式组成

var Schedule = mongoose.Schema({
  StartType: Number,
  StartDateTime: Date,
  CollectionList: [CollectionSchema]
});

var CollectionSchema = mongoose.Schema({
  CollectionID: Number,
  CollectionName: String,
  chdata: [ChannelSchema]
});

var ChannelSchema = mongoose.Schema({
  ADChannelName: String,
  ADChannel: Number,
  ADChannelType: Number,
  DisplayColor: String,
  Command: String
});

Schedule = mongoose.model('schedule', ScheduleSchema);
Collection = mongoose.model('collection', CollectionSchema);
Channel = mongoose.model('channel', ChannelSchema);

Schedule.find({}, function(err, data) {
  if (err) {
    console.log(err);
  } else {
    console.log(data);
  }
});

所以我可以找到Schedule,但是我想找到Collection和Channel对象。

如何使用猫鼬找到它们?

1 个答案:

答案 0 :(得分:0)

您可以使用此:

https://www.npmjs.com/package/mongoose-deep-populate

Schedule.find({}, function (err, schedules) {
   Schedule.deepPopulate(schedules, 'CollectionList.chdata', function (err, users) {
      // now each Schedule document includes CollectionList and each CollectionList includes chdata
   })
})