Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two OR-queries with AND in Mongoose

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?

like image 998
Sonson123 Avatar asked Nov 07 '12 15:11

Sonson123


People also ask

Can Mongoose queries be chained?

The Mongoose Query class provides a chaining interface for finding, updating, and deleting documents.

What is the difference between schema and model in Mongoose?

Mongoose Schema vs. Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

Can I use MongoDB and Mongoose together?

yes you should, its a good practice. Mongoose requires a connection to a MongoDB database. You can use require() and connect to a locally hosted database with mongoose.


1 Answers

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) {           ...       }); 
like image 100
JohnnyHK Avatar answered Oct 12 '22 15:10

JohnnyHK