在猫鼬中将两个OR查询与AND结合 [英] Combine two OR-queries with AND in Mongoose

查看:72
本文介绍了在猫鼬中将两个OR查询与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

如何在猫鼬中将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猫鼬发布:

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查询与AND结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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