I have 2 model users and user_verifications. user have username and email, and so does user_verification.
Before I insert data to user, I insert the data in user_verification first. So, I want to know if username or email is already registerered.
This is how I do it.
User.count({email: email}, function(err, count) {
if (count > 0) return false;
else User.count({username: username}, function(err, count) {
if (count > 0) return false;
else UserVerification.count({email: email}, function(err, count) {
if (count > 0) return false;
else UserVerification.count({username: username}, function(err, count) {
if (count > 0) return false;
return true;
});
});
});
});
But this is somehow annoying as I have to doing the same thing over and over again. Is there a better approach?
Thanks.
One thing that might help is to use an $or query so that you don't have to make two separate querys to the same collection.
User.count({ $or : [ { email : email } , { username : username } ] },
function () {...} );
You might also want to use an async library (such as async
) so that you can make these calls in parallel since they aren't dependent on one another.
async.parallel({
user: function(cb) {
User.count({$or : [ {email:email}, {username:username}]}, cb);
},
verification: function(cb) {
UserVerification.count({$or : [{email:email}, {username:username}]}, cb);
}
},
function (err, results) {
return !(results.user > 0 || results.verification > 0)
};