如何使用.where()后填充mongoose
所以我有两个模式
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 });
我想有一个查询只返回如果活动/显示在这两个类别/子类别。 我遇到的麻烦是如何在填充后正确设置categoryId的filter。 这是我到目前为止
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'); }); };
唯一的问题是即使当我有一个类别的显示=假它仍然会返回。
有一种特殊的方式来构build填充引用的查询条件。 从文档:
查询条件和其他选项
如果我们想根据他们的年龄填充我们的粉丝arrays,select他们的名字,最多只能返回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()