Is it possible to do a find inside a find on Node with Mongoose?
I'm letting a user change their email address, but I have to make sure the email hasn't been used by any other user before I save the new email.
I want to do this:
/*************************************************************
* MY_USER - PROFILE UPDATE
*************************************************************/
app.put('/api/myuser/info', auth, function(req, res) {
serverLog.log(req, production, {});
// User ID
var myUserID = req.session.passport.user._id;
if ( myUserID && validateID(myUserID) ) {
User.findOne({
_id: myUserID
}, function(err, data) {
if (err) throw err;
if (data == null) {
res.sendStatus(401);
console.log(401);
}
// Data
else {
// Update Email
if (req.body.email) {
// Check valid email
if ( validateEmail(req.body.email) ) {
console.log('validateEmail');
// Check Unique Email
User.findOne({
'local.user.info.email': email
}, function(err, user) {
if(err) return err;
if ( user ) {
// Email already in use
res.status(400).send('ERROR: Email Already in Use');
return;
}
console.log('uniqueEmail ' + true);
// Update email
user.local.user.info.email = req.body.email;
})
}
// Bad Email
else {
res.status(400).send('ERROR: Not a propper Email');
return;
}
}
// SAVE USER DATA
if ( info_sent ) {
user.save(function(err, data) {
if (err) throw err;
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(data.local.user.info, null, 3));
return;
});
}
// NO INFO WAS SENT
else {
res.status(400).send('ERROR: No information was sent.');
return;
}
}
});
}
// Bad / No User ID
else {
res.sendStatus(401);
}
});
I find the user, then check if email is in use How would one go about doing this?