我正在尝试将过滤器应用到mongo查找查询中。其思想是,如果筛选器有值,mongo选择器将限制返回的内容,但如果没有指定筛选器(筛选器具有空值或默认值),则不应限制查询。如果指定了筛选器,我知道如何使过滤器工作,但我不确定如果没有指定筛选器,如何确保它返回未经筛选的筛选器。如果筛选器未指定或默认值为默认值,如何使find查询返回集合中的所有文档?
FYI:我在一个Meteor项目中使用它,并将使过滤器成为一个会话变量,以使返回的内容具有动态。
示例集合:
/* example documents in SampleCollection
{ name: "sample1", fieldA: "foo", fieldB: "foo" }
{ name: "sample2", fieldA: "foo", fieldB: "bar" }
{ name: "sample3", fieldA: "bar", fieldB: "foo" }
{ name: "sample4", fieldA: "bar", fieldB: "bar" }
*/示例JS代码:
var filters = {
fieldA: null,
fieldB: null
};
var getFieldASelector = function () {
if (filters.fieldA) {
return { $eq: fieldA };
} else {
/* fieldA has a falsey value which is the default
and therefore should not limit the find query */
// not sure what to return here
return {};
};
};
var getFieldBSelector = function () {
if (filters.fieldB) {
return { $eq: fieldB };
} else {
/* fieldB has a falsey value which is the default
and therefore should not limit the find query */
// not sure what to return here
return {};
};
};
var results = SampleCollection.find({
fieldA: getFieldASelector(),
fieldB: getFieldBSelector()
});在本例中,results应该返回所有四个文档。如果是filter = { fieldA: "foo", fieldB: null };,那么results应该返回文档sample1和sample2。
发布于 2015-12-17 16:05:28
假设每个文档都有两个键,您可以只使用return {$ne:null}。如果要使If工作,如果存在键,但其值为空,则还可以使用return {$exists:true}。
发布于 2015-12-17 15:31:52
我可以建议您创建一个selector对象并根据给定的过滤器填充它。但我不太确定这是不是你想要的。
function getResults(filter){
var selector = {};
// what this does is filters aways keys with non-truthy values
Object.keys(filter).reduce(function (prev, curr){
var val = filter[curr];
if (!!val)
prev[curr] = filter[curr];
return prev;
}, selector);
return SampleCollection.find(selector);
}当您实际想要使用非真实值(如0或空字符串)筛选字段时,会发现意外行为。
https://stackoverflow.com/questions/34337881
复制相似问题