23

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!

});
CaribouCode
  • 13,998
  • 28
  • 102
  • 174

1 Answers1

76

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'
Andrew Dunai
  • 3,061
  • 19
  • 27
  • 8
    Is there a way to prioritize one value over another? For example, search all email addresses first, then look for phone if none exist. – Aaron Ash Jan 29 '17 at 22:45