问题描述
例如,在任何给定的运行时,
As an example, at any given runtime,
Books = {
CatSelect:[SciFi,幽默 ,历史],
最小页数:[300,50,500]
};
如果我手动编写如下所示在查找
函数中查询,它按预期工作,并查找页数大于指定类别中指示金额的图书。
If I manually write the query in the find
function as below, it works as intended and finds the books with number of pages greater than the indicated amounts in indicated categories.
MyCollection.find({ $or: [ { Category: Books.CatSelect[0], Pages : { $gte: Books.MinPages[0] } }, { Category: Books.CatSelect[1], Pages : { $gte: Books.MinPages[1] } } ] }).execFind(function(err,result){
...
}
但问题是我不知道会选择多少类别,上面的例子是设置的 .find
2个类别的示例。
But the problem is I would not know how many of the categories will be selected, the above example is set .find
example for 2 categories.
如何动态地将不同数量的条件放入 .find
function?
How to put a varying number of criteria dynamically into the .find
function?
当然我可以将所有条件放在一个字符串中,但是查询不是字符串也不是JSON,所以我有点迷失。
Naturally I can put all the criteria in a string, but query is not a string nor a JSON, so I'm kinda lost.
推荐答案
您可以通过编程方式构建查询对象,根据选择。例如:
You can build up your query object programmatically, based on the selections. For example:
var selections = [0, 1];
var query = { $or: [] };
for (var i=0; i<selections.length; i++) {
var selection = selections[i];
query.$or.push({
Category: Books.CatSelect[selection],
Pages: { $gte: Books.MinPages[selection] }
});
}
MyCollection.find(query).exec(function(err, result){
//...
}
这篇关于如何在mongoose.find中执行动态数量的条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!