Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do a conditional Mongoose query that uses AND and OR? [duplicate]

I would like to do a complex and/or query with Mongoose. Here is some pseudocode that shows what I'm trying to do:

Find persons where (
  (date_begin == null || date_begin <= today)
  && (date_end == null || date_end >= tomorrow)
)

Here is my failing attempt at real Mongoose code:

  query = Person
    .find()
    .where('date_begin').equals(null).or.where('date_begin').lte(today)
    .where('date_end').equals(null).or.where('date_end').gte(tomorrow)

Any suggestions would be greatly appreciated! (FYI, today and tomorrow are being set fine, it's the Mongoose syntax I am asking about.)

like image 780
dylanized Avatar asked Oct 14 '25 23:10

dylanized


1 Answers

Dylanized,

You could do the following, by using the mongodb Logical Query Operators directly like this:

  Person.find({
      $and: [
          { $or: [{date_begin: null}, {date_begin: {$lte : today}}] },
          { $or: [{date_end: null}, {date_end: {$gte : tommorow}}] }
      ]
  }, function (err, results) {
      ...
  }
like image 183
Abdullah Rasheed Avatar answered Oct 17 '25 12:10

Abdullah Rasheed