Mongoose search method with condition $ or does not work properly

I recently started using MongoDB with Mongoose on Nodejs.

When I use the Model.find method with the condition $or and _id , Mongoose does not work properly.

This does not work:

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

By the way, if I delete the '_id' part, it works!

 User.find({ $or: [ { 'name': param }, { 'nickname': param } ] }, function(err, docs) { if(!err) res.send(docs); }); 

And in the MongoDB shell, both work correctly.

+80
mongodb mongoose
Sep 12 2018-11-11T00:
source share
3 answers

I solved this through googling:

 var ObjectId = require('mongoose').Types.ObjectId; var objId = new ObjectId( (param.length < 12) ? "123456789012" : param ); // You should make string 'param' as ObjectId type. To avoid exception, // the 'param' must consist of more than 12 characters. User.find( { $or:[ {'_id':objId}, {'name':param}, {'nickname':param} ]}, function(err,docs){ if(!err) res.send(docs); }); 
+158
Sep 13 '11 at 12:07
source share

I beg everyone to use Mongoose's query-building language and promises instead of callbacks:

 User.find().or([{ name: param }, { nickname: param }]) .then(users => { /*logic here*/ }) .catch(error => { /*error logic here*/ }) 

Learn more about Mongoose Queries .

+19
Jan 20 '18 at 6:23
source share

According to mongoDB documentation: "... That is, for MongoDB to use indexes to evaluate $ or expression, all sentences in $ or expression must be supported by indexes."

So, add indexes for the other fields and this will work. I had a similar problem and this solved it.

You can read more here: https://docs.mongodb.com/manual/reference/operator/query/or/

0
Nov 17 '17 at 16:09
source share



All Articles