【问题标题】:Populate multiple references (subdocuments) AND select SPECIFIC fields填充多个参考(子文档)并选择特定字段
【发布时间】:2020-04-18 08:07:22
【问题描述】:

使用 Mongodb、mongoose、nodejs、express....

我有这样的结构...

const EventSchema = new mongoose.Schema({
  eventDate: {
    type: Date
  },
  attendees: [
    {
      type: mongoose.Schema.ObjectId,
      ref: 'Person'
    }
  ],
  staff: [
    {
      person: {
        type: mongoose.Schema.ObjectId,
        ref: 'User'
      },
      department: {
        type: String,
        enum: ['photography', 'data-entry', 'mgmt', 'other']
      }
    }
  ]
});

我知道如何填充('参加者部门')。这工作正常并返回两者的所有数据。但是,因为我基本上处理的是多个填充,我如何选择应该为与会者和部门检索的特定字段?

【问题讨论】:

  • 请向我们展示您到目前为止所做的尝试。
  • populate('参加者部门')
  • 亲爱的,请不要在评论部分发布您的代码。显示整个代码并提及您想要的字段。
  • @WebDevGuy2 这可能会有所帮助:How to select specific field in nested populate in mogoose
  • @MianMuhammad 谢谢,但我正在尝试在 MULTIPLE 填充中选择特定字段

标签: node.js mongodb mongoose


【解决方案1】:

您可以按如下方式编写查询,以填充多个值并仅返回您需要的特定字段

Event.find().populate([{
    path: 'attendees',
    model: 'Person',
    select: '_id name profile_pic' //Fields you want to return in this populate
}, {
    path: 'staff.person',
    model: 'User',
    select: '_id name profile_pic' //Fields you want to return in this populate
}])

【讨论】:

    猜你喜欢
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 2011-01-21
    • 2021-04-19
    • 2013-01-15
    • 1970-01-01
    相关资源
    最近更新 更多