gpt4 book ai didi

javascript - 如何在 mongo 选择器中使用过滤器的默认值?

转载 作者:行者123 更新时间:2023-11-27 23:33:31 25 4
gpt4 key购买 nike

我正在尝试将过滤器应用于 mongo 查找查询。这个想法是,如果过滤器具有值,mongo 选择器将限制返回的内容,但如果未指定过滤器(过滤器具有空值或默认值),则它不应限制查询。我知道如果指定了过滤器如何让过滤器工作,但我不确定如果没有指定过滤器如何确保它返回未过滤的情况。如果未指定过滤器或使用默认值,如何让查找查询返回集合中的所有文档?

仅供引用:我在 Meteor 项目中使用它,并将过滤器设置为 session 变量,以使返回的内容动态化。

示例集合:

/* 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()
});

在此示例中,结果 应返回所有四个文档。如果 filter = { fieldA: "foo", fieldB: null };results 应返回文档sample1 和sample2。

最佳答案

假设每个文档都有两个键,您可以返回 {$ne:null}。如果你想让 if 在键存在但值为 null 时起作用,你也可以 return {$exists:true}

关于javascript - 如何在 mongo 选择器中使用过滤器的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34337881/

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