Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose findOne with 'either or' query [duplicate]

Tags:

I have a Mongo user database that I'm querying with Mongoose. I want to do findOne to determine if a user already exists. I want it to first search if a user already exists with an email, and if it doesn't it should then search to see if a user exists with a phone. Does this have to be done in 2 separate queries or can it be rolled into one?

User.findOne({ email: req.body.email }).exec(function(err, user){    if (user) //user already exists with email   else //no users with that email but we haven't checked phone number yet!  }); 
like image 530
CaribouCode Avatar asked Mar 17 '15 12:03

CaribouCode


1 Answers

Why not just use $or operator?

User.findOne({$or: [     {email: req.body.email},     {phone: req.body.phone} ]}).exec(function(err, user){     if (user) {} //user already exists with email AND/OR phone.     else {} //no users with that email NOR phone exist. }); 

Here's the pseudo-SQL equivalent:

SELECT * FROM users WHERE email = '%1' OR phone = '%2' 
like image 197
Andrew Dunai Avatar answered Sep 29 '22 13:09

Andrew Dunai