【问题标题】:How can I find sub documents using Mongoose?如何使用 Mongoose 查找子文档?
【发布时间】:2018-08-03 19:59:54
【问题描述】:

我有 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 对象。

如何使用 mongoose 找到它们?

【问题讨论】:

  • 如果需要在 CollectionSchema 和 ChannelSchema 对象中搜索,请使用聚合
  • 您要查找collectionchannel?你想通过哪个属性来查找?

标签: node.js database mongodb mongoose


【解决方案1】:

你可以用这个:

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
   })
})

【讨论】:

    猜你喜欢
    • 2016-03-24
    • 1970-01-01
    • 2017-04-15
    • 2014-11-27
    • 2020-04-24
    • 2013-05-26
    • 1970-01-01
    • 2014-03-21
    相关资源
    最近更新 更多