问题
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