所以我有两个架构
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
});
和
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
});
我希望只有在类别/子类别中的active / display为true时才返回查询。我遇到的问题是如何在填充后正确设置categoryId的过滤器。这是我到目前为止所拥有的
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');
});
};
唯一的问题是即使我有一个display = false的类别,它仍会被返回。
答案 0 :(得分:19)
要为填充的引用构建查询条件,可以使用特殊方法引用here:
查询条件和其他选项
如果我们想根据他们的年龄填充我们的粉丝阵列,选择他们的名字,最多返回其中任何5个,该怎么办?
Story .find(...) .populate({ path: 'fans', match: { age: { $gte: 21 }}, select: 'name -_id', options: { limit: 5 } }) .exec()
所以在你的情况下,你需要做类似的事情:
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()