Combine two OR-queries with AND in Mongoose

node.jsMongodbMongoose

node.js Problem Overview


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)

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

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

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

node.js Solutions


Solution 1 - node.js

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:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSonson123View Question on Stackoverflow
Solution 1 - node.jsJohnnyHKView Answer on Stackoverflow