So i have two schemas
var subcategories = new Schema({
//the category being populated needs to be the same case ;
categoryId: [{ type: Schema.ObjectId, ref: 'categories' }],
name: String,
description: String,
display: Boolean,
active: Boolean,
sortOrder: Number,
createDate: Date,
updateDate: Date,
type: String,
startDate: Date,
endDate: Date,
authorId: String
});
And
var categories = new Schema({
name: String,
description: String,
display: Boolean,
active: Boolean,
sortOrder: Number,
createDate: Number,
updateDate: Number,
type: String,
startDate: Date,
endDate: Date,
authorId: String
});
And I want to have a query to only return if active/display is true in both category/subcategory. What I'm having trouble with is how to properly set the filter for categoryId after a populate. Here is what I have so far
exports.generateList = function (req, res) {
subcategories
.find({})//grabs all subcategoris
.where('categoryId').ne([])//filter out the ones that don't have a category
.populate('categoryId')
.where('active').equals(true)
.where('display').equals(true)
.where('categoryId.active').equals(true)
.where('display').in('categoryId').equals(true)
.exec(function (err, data) {
if (err) {
console.log(err);
console.log('error returned');
res.send(500, { error: 'Failed insert' });
}
if (!data) {
res.send(403, { error: 'Authentication Failed' });
}
res.send(200, data);
console.log('success generate List');
});
};
The only problem is even when i have a category with display = false it will still get returned.
To build query conditions for populated references there are special ways that can be referenced here:
Query conditions and other options
What if we wanted to populate our fans array based on their age, select just their names, and return at most, any 5 of them?
Story .find(...) .populate({ path: 'fans', match: { age: { $gte: 21 }}, select: 'name -_id', options: { limit: 5 } }) .exec()
So in your case, you need to do something similar to this:
subcategories
.find({})//grabs all subcategoris
.where('categoryId').ne([])//filter out the ones that don't have a category
.where('active').equals(true)
.where('display').equals(true)
.populate({
path: 'categoryId',
match: {
active: true,
display: true,
}
})
.exec()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With