Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

Basically I want to join two OR-queries with AND operator in Mongoose, as you can see in the following query:

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

I have tried to implement the same query in the NodeJS module, refer the following code:

/********** 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 the above code didn't provide me the desired output. Can someone supervise me on how to join two conditions of myModule1 and myModule2 with AND in Mongoose? 

1 Answer

0 votes
by (108k points)
edited by

In MongoDB, you can simply use the following code to create your query object directly:

  Test.find({

      $and: [

          { $or: [{a: 1}, {b: 1}] },

          { $or: [{c: 1}, {d: 1}] }

      ]

  }, function (err, results) {

      ...

  }

Inside your 'or' field you can mention your module1 and module 2 respectively. The basic syntax is:

{ $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }

You can simply provide here your expressions on which you have to perform AND operation. 

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer

Browse Categories

...