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! });
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With