如何使用AND和OR进行条件Mongoose查询

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

本文关键字:条件 Mongoose 查询 OR 何使用 AND      更新时间:2023-09-26

我想用Mongoose做一个复杂的和/或查询。下面是一些伪代码,显示了我正在尝试做的事情:

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

以下是我对真正的Mongoose代码的失败尝试:

  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)

如有任何建议,我们将不胜感激!(仅供参考,今天和明天都很好,这是我所问的Mongoose语法。)

去矿化,

通过像这样直接使用mongodb逻辑查询运算符,您可以执行以下操作:

  Person.find({
      $and: [
          { $or: [{date_begin: null}, {date_begin: {$lte : today}}] },
          { $or: [{date_end: null}, {date_end: {$gte : tommorow}}] }
      ]
  }, function (err, results) {
      ...
  }