将两个 OR 查询与 Mongoose 中的 AND 结合起来 [英] Combine two OR-queries with AND in Mongoose

查看:26
本文介绍了将两个 OR 查询与 Mongoose 中的 AND 结合起来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Monoose 中将两个 OR 查询与 AND 结合起来,就像在这个 SQL 语句中一样:

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

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

我在 NodeJS 模块中尝试了这个,它只从主应用程序获取模型对象:

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

/********** 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});
}

但这行不通,所有的 OR 条件都会像这条 SQL 语句一样连接在一起:

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

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

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

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

推荐答案

直接创建查询对象可能是最简单的:

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) {
      ...
  }

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

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

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

这篇关于将两个 OR 查询与 Mongoose 中的 AND 结合起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆