将动态条件添加到猫鼬中,在同一查询中找到nodejs。

时间:2018-08-24 05:38:10

标签: javascript node.js mongodb mongoose

我正在尝试使用猫鼬库添加动态条件

var and_cond = { $and: [] };
var or_cond = { $or: [] };
and_cond.$and.push ({ "doc_no" :  /first/i  })
or_cond.$or.push ({ "doc_type" : /third/i  })

TRModel.find(
            and_cond,
            or_cond
       )

我期望可以在查询中同时满足 AND OR 条件的事情

以上内容以突然的查询结尾,显然是错误的。

  

title_records.find({'$ and':[{doc_no:/ first / i}]},{字段:{   '$ or':[{doc_type:/ third / i}]}})

2 个答案:

答案 0 :(得分:1)

有两个问题:

  1. 您正在尝试使用两个顶级逻辑运算符。据我所知,您需要在$and$or$nor的集合中只有一个顶级运算符。但是,您可以在其中嵌套任意多个。
  2. 当您真正想要做的是将两个对象合并时,您将传递两个单独的对象。

您似乎正在尝试执行查询,以便找到同时符合$and条件和$or条件的所有文档。在这种情况下,请尝试以下操作:

TRModel.find({
    $and: [
        and_cond,
        or_cond
    ]
});

但是,如果要使用一个或另一个,则可以将顶级$and更改为$or

TRModel.find({
    $or: [
        and_cond,
        or_cond
    ]
});

答案 1 :(得分:1)

您首先需要确保自己是matching the mongoose find parameters,具体定义为:

Areat

例如

import java.util.*;
public class Triangle
{
public void main1()
{
    this.main1();
}
public void main2()
{
    this.main2();
}
public void main3()
{
    this.main3();
}
public static void main(String args[])
{
    int M , a , b , c , z , y , A , B , C;
    Scanner in = new Scanner(System.in);
    System.out.println("Press 1 to find the perimeter\nPress 2 to find the area\nPress 3 to find the missing height");
    M = in.nextInt();
    Triangle ob = new Triangle();
    switch(M)
    {
        case 1:
        ob.main1();
        break;
        case 2:
        ob.main2();
        break;
        case 3:
        ob.main3();
        break;
        default:
        System.out.println("Sorry, I can only do 3 operations.\nThank You!!!!!");
       }
    }
}

因此,您必须确保最终结果是有一个对象进入查找的条件部分。

接下来的事情是,您必须确保有一个操作员from these types

MyModel.find({ <conditions> }, { <projections> }, { <options> }, <callback function>); MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {}); $and$or

作为您的顶层,然后您可以将其他人嵌套在其中。 就像您可能拥有顶层$not,其中包含多个$not