Ayeye Brazo
Ayeye Brazo

Reputation: 3476

Mongoose find with or operator failing

I have an input with autocomplete and I want to find user by _id, name or email.

This query is working fine but it search just using name or email:

  var matchRegexp = new RegExp(_.escapeRegExp(req.query.match), 'i');

  User.find(
    {$or: [{email: matchRegexp}, {name: matchRegexp}]},
    {email: 1, name: 1, _id: 0}
    ).limit(limitResults).exec(
    function(error, users) {
      if (error) {
        return res.status(400).json({
          "message": "Query failed",
        });
      } else {
        return res.json({
          "results": users
        });
      }
    }
  );

If I try to add _id at the $or it fails searching by name or email but it works with _id:

{$or: [{email: matchRegexp}, {name: matchRegexp}, {_id: req.query.match}]}

How can I let it work using all 3 options?

EDIT:

This is the error:

CastError: Cast to ObjectId failed for value "ayeye" at path "_id" for model "User"

it is not considering at all name and email...

Upvotes: 1

Views: 137

Answers (1)

Ashh
Ashh

Reputation: 46441

Because your match string is not a valid ObjectId you are getting this error.

So here you can first check the validation for valid ObjectId and then make a criteria accordingly.

const ObjectId = require('mongoose').Types.ObjectId

const criteria = { $or: [{ email: matchRegexp },{ name: matchRegexp }] }

If (ObjectId.isValid(matchRegexp)) {
  criteria.$or.push({ _id: matchRegexp })
}

User.find(criteria, { email: 1, name: 1, _id: 0 }).limit(limitResults).exec()

Upvotes: 1

Related Questions