Is it possible to have condition in mongoose populate

坚强是说给别人听的谎言 提交于 2021-01-29 03:29:36

问题


I have a sub document called services in a collection it contains serviceID and type. serviceID is referred to two collections internalservice and externalservice varies based on the type field.

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


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

Above two are lookup collection. And here the company collection

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

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

Here, i want to populate service description based on type.

Is it possible to have conditional path at populate?

Here's my code

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

               console.log(companyInfo);
             });

This populates internal service description but i need to populate external service description for type externalservice. When i have two populate the second populate replaces the result with null for unmatched documents.


回答1:


You can include in populate where conditions like:

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

Here is the Mongoose Populate Documentation



来源:https://stackoverflow.com/questions/40339260/is-it-possible-to-have-condition-in-mongoose-populate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!