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?
The Mongoose Query class provides a chaining interface for finding, updating, and deleting documents.
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.
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.
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) { ... });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With