Categories
JavaScript Answers

How to fix Mongoose’s find method with $or condition does not work properly with JavaScript?

Spread the love

To fix Mongoose’s find method with $or condition does not work properly with JavaScript, we set $or to an array with the conditions we’re searching for.

For instance, we write

const ObjectId = require("mongoose").Types.ObjectId;
const objId = new ObjectId(param.length < 12 ? "123456789012" : param);

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

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

We get the results from the docs parameter in the callback.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *