Does mongoose provide a way to find all referenced documents from a previous query' result?
For example:
Product
.find(query)
.exec(function(err, results) {
...
Product
.find({
'$or': [
// get all products where _id is in results.associatedProducts[]
]
})
...
});
I wasn't able to find a way to do this natively with mongoose, see below for working solution.
Product
.find(query)
.exec(function(err, products) {
...
var associatedSoftware = products.reduce(function(memo, current) {
if(current.features && current.features.associatedSoftware) {
return memo.concat(current.features.associatedSoftware.map(function(item) {
return item._id;
}));
}
return memo;
}, []);
Product.find({
'$or': [
...
{ '_id': { '$in': associatedSoftware } }
...
]
})
.exec(function(err, associated) {
...
});
});
Yes.
You can use query population .
Product
.find(query)
.populate('associatedProducts')
.exec(function(err, results) {
// ...
});
This will return you an object formatted like this:
var product = {
foo: bar,
associatedProducts: [
// Here are the associated products
{
// Product Object
},
{
// Product Object
},
{
// Product Object
}
]
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.