node.js 将两个 OR 查询与 Mongoose 中的 AND 结合起来

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13272824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:36:18  来源:igfitidea点击:

Combine two OR-queries with AND in Mongoose

node.jsmongodbmongoose

提问by Sonson123

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

我想在 Monoose 中将两个 OR 查询与 AND 结合起来,就像在这个 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:

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

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

How can I combine the two conditions of myModule1and myModule2with AND in Mongoose?

如何在 Mongoose 中将myModule1and的两个条件myModule2与 AND结合起来?

回答by JohnnyHK

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#andhelper that's available in recent 3.x Mongoose releases:

但是您也可以使用Query#and最近 3.x Mongoose 版本中提供的帮助程序:

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