Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将$and和$or查询添加到MongoDB查询的结构中-必须是非空数组_Javascript_Arrays_Node.js_Mongodb_Mongodb Query - Fatal编程技术网

Javascript 将$and和$or查询添加到MongoDB查询的结构中-必须是非空数组

Javascript 将$and和$or查询添加到MongoDB查询的结构中-必须是非空数组,javascript,arrays,node.js,mongodb,mongodb-query,Javascript,Arrays,Node.js,Mongodb,Mongodb Query,我试图将多个查询组合到一个对象中:用户可以根据预选的选项构建查询,并选择and或or运算符。所有查询都正确输出,但当将它们放入对象时,我得到“Error:$and/$or/$nor必须是非空数组” 例如,假设我们有查询a、b、c、d和E 输出应该是:{$和[a$和:[b$和:[c$和:[d,e]]]} 这样,如果他们选择另一个操作员,操作仍然保持不变 代码如下: function nestOps(ops, queries) { let queryObj = {}; if (ops.len

我试图将多个查询组合到一个对象中:用户可以根据预选的选项构建查询,并选择and或or运算符。所有查询都正确输出,但当将它们放入对象时,我得到“Error:$and/$or/$nor必须是非空数组”

例如,假设我们有查询a、b、c、d和E 输出应该是:{$和[a$和:[b$和:[c$和:[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;
}
我尝试过通过递归来实现它,但是,我的堆栈非常臃肿(即使堆栈大小增加了),我看不到如何使用tailing方法(“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: {…}}

您可以使用单个
$和
来简化它,而不是创建嵌套的
$和

{ property: { $and: [ {filter}, {filter} ] }}

为什么不
{$and:[这里的所有选项]}
而不是嵌套and?我不确定这是否是有效的
$和
操作。嗯,我早该想到的,我会尝试一下并让你知道,谢谢!是的,很好用,谢谢。我可以为这个问题创建单独的答案吗?这将有助于我扩大我的个人资料。