How to use Mongoose’s find method with $or?

Sometimes, we want to use Mongoose’s find method with $or.

In this article, we’ll look at how to use Mongoose’s find method with $or.

How to use Mongoose’s find method with $or?

To use Mongoose’s find method with $or, we can set $or to an array of properties and values we’re looking for.

For instance, we write

User.find({
    $or: [{
      '_id': objId
    }, {
      'name': param
    }, {
      'nickname': param
    }]
  },
  (err, docs) => {
    if (!err) {
      //...
    }
  });

to call User.find with an object with the $or property set to an array we’re looking for.

We’re searching for a User entry with _id set to objId or name set to param or nickname set to param.

Then callback is run when the query is done and the docs parameter has the query results.

Conclusion

To use Mongoose’s find method with $or, we can set $or to an array of properties and values we’re looking for.