【问题标题】:Is it possible to have condition in mongoose populate是否有可能在猫鼬填充条件
【发布时间】:2017-03-13 08:43:54
【问题描述】:

我在集合中有一个名为services 的子文档,它包含serviceIDtypeserviceID 引用两个集合 internalserviceexternalservice 根据类型字段而有所不同。

internalServices:[{
           serviceID:ObjectId('0000000000000'),
           serviceDesc:'sweeping'
         },
         {
           serviceID:ObjectId('0000000000000'),
           serviceDesc:'floor cleaning'
         }]


 externalServices:[{
               serviceID:ObjectId('0000000000000'),
               serviceDesc:'painting'
             },
             {
               serviceID:ObjectId('0000000000000'),
               serviceDesc:'white washing'
             }]

以上两个是查找集合。这里是公司收藏

   _id:"xxxxxxxxxxxxxxxx",
   name: 'xxxx',
   Address:'xxx',

    services:[{
           serviceID:ObjectId('0000000000000'),
           type: internalservice
         },
         {
           serviceID:ObjectId('0000000000000'),
           type: externalservice
         }]

在这里,我想根据类型填充服务描述。

是否可以在填充时设置条件路径?

这是我的代码

Company.findOne({"_id": mongoose.Types.ObjectId(req.params.companyID)},
                {})
             .populate('services.serviceID','serviceDesc','InternalService')
             .exec(function (err, companyInfo) {

               console.log(companyInfo);
             });

这会填充内部服务描述,但我需要填充外部服务类型的外部服务描述。当我有两个填充时,第二个填充将结果替换为 null 以获得不匹配的文档。

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-populate


    【解决方案1】:

    您可以在填充 where 中包含以下条件:

    Story
    .find(...)
    .populate({
      path: 'fans',
      match: { age: { $gte: 21 }},
      select: 'name -_id',
      options: { limit: 5 }
    })
    .exec()
    

    Here is the Mongoose Populate Documentation

    【讨论】:

      猜你喜欢
      • 2021-10-07
      • 2020-01-17
      • 2015-11-27
      • 2018-02-12
      • 2015-07-13
      • 2016-10-10
      • 2020-11-19
      • 2019-09-16
      相关资源
      最近更新 更多