gpt4 book ai didi

javascript - 如何在 Mongoose 填充后使用 .where()

转载 作者:IT老高 更新时间:2023-10-28 13:13:14 25 4
gpt4 key购买 nike

所以我有两个模式

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 的过滤器。这是我到目前为止所拥有的

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 的类别,它仍然会被返回。

最佳答案

要为填充的引用构建查询条件,有一些特殊的方法可以引用 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()

所以在你的情况下,你需要做类似的事情:

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()

关于javascript - 如何在 Mongoose 填充后使用 .where(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21996110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com