【发布时间】:2020-02-23 16:46:42
【问题描述】:
我正在尝试将多个查询组合到一个对象中:用户可以从预先选择的选项构建查询并选择 and 或 or 运算符。查询都正确输出,但是当将它们放入对象中时,我得到“错误:$and/$or/$nor must be nonempty array”。
例如假设我们有查询 a AND b AND c AND d AND e 输出应该是:{$and[a,$and:[b,$and:[c,$and:[d,e]]]]} 这样如果他们选择另一个操作员,操作仍然保持不变
代码如下:
function nestOps(ops, queries) {
let queryObj = {};
if (ops.length > 1) {
let querySet = {};
querySet[`$${ops[ops.length - 1]}`] = [queries[ops.length - 1], queries[ops.length]];
for (let i = ops.length - 2; i > 0; i--) {
let next = {};
next[`$${ops[i]}`] = querySet;
querySet = {};
let nextIdx = i - 1;
if (nextIdx > 0) {
querySet[`$${ops[nextIdx]}`] = [queries[i], next];
i--;
}
else {
querySet = next;
}
}
queryObj[`$${ops[0]}`] = [querySet, queries[0]];
}
else {
queryObj[`$${ops[0]}`] = [...queries];
}
return queryObj;
}
我已经尝试通过递归来实现它,但是我的堆栈非常臃肿(即使堆栈大小增加了)并且我看不到如何使用拖尾方法(“return nextCall()”),因为我必须返回上一个查询andded 或 orred,如果没有先分配,我真的无法做到。
这是控制台输出:
Output Object
$and: Array(2)
0:
$and: Array(2)
0: {questions: {…}}
1:
$and: // could be an error here but, I don't understand why
$and: Array(2)
0: {$or: Array(2)} //this happens due to a query, it is not an error
1: {questions: {…}}
Operators
["and", "and", "and", "and"]
Queries
(5) [{…}, {…}, {…}, {…}, {…}]
0: {questions: {…}}
1: {completedAt: {…}}
2: {questions: {…}}
3: {$or: Array(2)}
4: {questions: {…}}
【问题讨论】:
-
为什么不用
{$and: [all the options here]}而不是嵌套and?我不确定这是否是有效的$and操作。 -
嗯,我早该想到的,我试试看告诉你,谢谢!
-
是的,它工作正常,谢谢。
-
我可以为此创建单独的答案吗?这将帮助我发展我的个人资料。
标签: javascript arrays node.js mongodb mongodb-query