Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

Recently I start using MongoDB with Mongoose on Nodejs.

When I use the Model.find method with $or condition and _id field, 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 remove the '_id' part, this DOES work!

User.find({ 

$or: [ 

{ 'name': param }, 

{ 'nickname': param } 

    ] 

}, function(err, docs) { 

if(!err) res.send(docs); 

});

And in MongoDB shell, both work properly.

2 Answers

0 votes
by (106k points)

I solved it through googling:

var ObjectId = require('mongoose').Types.ObjectId; 

var objId = new ObjectId( (param.length < 12) ? "123456789012" : param ); 

User.find( { $or:[ {'_id':objId}, {'name':param}, {'nickname':param} ]}, 

function(err,docs){ 

if(!err) res.send(docs); 

});

0 votes
by (107k points)

I would suggest you use Mongoose's query builder language and promises instead of using callbacks:

User.find().or([{ name: param }, { nickname: param }])

    .then(users => { /*logic here*/ })

    .catch(error => { /*error logic here*/ })

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
0 votes
2 answers
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...