6

How do I do an 'OR' operator with query builder in Mongoose?

I tried something like this: Find a user by ID or Username but it didn't work.

User.findOne({})
      .where( '_id', 'username').equals(param)
Matt
  • 609
  • 2
  • 12
  • 19
  • where is the or in that? can you write pseudocode of what you want to achieve? which version of Mongoose do you use? – boroboris Mar 28 '17 at 09:36
  • Well, @boroboris that is my question... how to do an OR in mongoose, I am using latest version of Mongoose – Matt Mar 28 '17 at 09:39
  • I wanted to ask about the specific or conditions you want to use. – boroboris Mar 28 '17 at 09:49
  • Oh sorry, I tried to pass an options inside the WHERE in this format '_id', 'username' – Matt Mar 28 '17 at 09:51
  • I've found the part of the answer here: http://stackoverflow.com/questions/7382207/mongooses-find-method-with-or-condition-does-not-work-properly so you can check that out too – boroboris Mar 28 '17 at 09:55

2 Answers2

11

Try something along those lines:

User.findOne({
     $or:[ 
       {'condition_1':param}, {'condition_2':param} 
     ]},
     function(err,docs){
       if(!err) res.send(docs);
     }
  });
boroboris
  • 1,548
  • 1
  • 19
  • 32
0

My solution

// Needed to user ObjectID comparison
const { ObjectID } = require('mongodb'); 

// Check if param is a valid ID otherwise is Username
let id_or_username = ObjectID.isValid(id) ? '_id' : 'username';

// Find post by ID or Username
Home
  .findOne({})
  .where(id_or_shortid).equals(id)
  .exec(callback)  
Matt
  • 609
  • 2
  • 12
  • 19