将两个or查询与Mongoose组合在一起

时间:2021-10-25 01:21:51

I want to combine two OR-queries with AND in Monoose, like in this SQL statement:

我想将两个或查询合并到一个单糖中,就像这个SQL语句:

SELECT * FROM ... WHERE (a = 1 OR b = 1) AND (c=1 OR d=1)

I tried this in a NodeJS module which only gets the model object from the main application:

我在NodeJS模块中尝试过,该模块只从主应用程序获取模型对象:

/********** Main application ***********/
var query = MyModel.find({});
myModule1.addCondition(query);
myModule2.addCondition(query);
query.exec(...)

/************ myModule1 ***************/
exports.addCondition = function(query) {
  query.or({a: 1}, {b: 1});
}

/************ myModule2 ***************/
exports.addCondition = function(query) {
  query.or({c: 1}, {d: 1});
}

But this doesn't work, all OR-conditions will get joined together like in this SQL statement:

但这不起作用,所有或条件都将像SQL语句一样连接在一起:

SELECT * FROM ... WHERE a = 1 OR b = 1 OR c=1 OR d=1

How can I combine the two conditions of myModule1 and myModule2 with AND in Mongoose?

如何将myModule1和myModule2的两个条件与Mongoose结合起来?

1 个解决方案

#1


125  

It's probably easiest to create your query object directly as:

将查询对象直接创建为:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

但是您也可以使用查询#和帮助器,它们在最近的3中可用。x猫鼬版本:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

#1


125  

It's probably easiest to create your query object directly as:

将查询对象直接创建为:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

但是您也可以使用查询#和帮助器,它们在最近的3中可用。x猫鼬版本:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });