首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >填充多个引用(子文档)并选择特定字段

填充多个引用(子文档)并选择特定字段
EN

Stack Overflow用户
提问于 2019-12-29 09:26:49
回答 1查看 61关注 0票数 0

使用Mongodb,mongoose,nodejs,express....

我有一个这样的结构。

代码语言:javascript
复制
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']
      }
    }
  ]
});

我知道如何填写(‘与会者部门’)。这样做可以很好地工作,并返回这两个函数的所有数据。但是,由于我主要处理的是多个填充,如何选择应该为与会者和部门检索的特定字段?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-13 18:06:54

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

代码语言:javascript
复制
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
}])
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59516242

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档