I am using Mongodb and the findOne feature:
User.findOne({$or: [{email: req.body.email}, {mobile: req.body.mobile}]}
However the issue I am facing is with req.body.email
and req.body.mobile
- in certain cases can be empty.
I have initially solved this using:
var toSearchSmartString = {$or: [{email: req.body.email}, {mobile: req.body.mobile}]};
if (req.body.email.length == 0) {
toSearchSmartString = {mobile: req.body.mobile};
} else if (req.body.mobile.length == 0) {
toSearchSmartString = {email: req.body.email};
}
then in the findOne, simply using:
User.findOne(toSearchSmartString);
So I want to check is this 'safe' todo? The reason I ask is this safe is because if I don't set the default value for toSearchSmartString and instead set it at the end of the if block (in a else) I get 'undefined' for the string.
I'm concerned that the findOne method may use the default toSearchSmartString before the if else condition has been checked? Am I right to concerned about this?
Alternatively is there some Mongodb function I can use to solve?
UPDATE: So after comments in answer below - having issues with the code:
I solved it by moving the var declaration above to where its used.
var contWithRegCallback = function(err, user) {
console.log(user);
}
if (req.body.email.length == 0) {
User.findOne({mobile: req.body.mobile}, contWithRegCallback);
} else if (req.body.mobile.length == 0) {
User.findOne({email: req.body.email}, contWithRegCallback);
} else {
User.findOne({$or: [{email: req.body.email}, {mobile: req.body.mobile}]}, contWithRegCallback);
}
Namely the user in the callback function keeps returning undefined. Shouldnt it be the contents fro the fineOne?