Ahmad Dogly Ahmad Dogly - 1 month ago 19
Node.js Question

check if user name and email in database using expressJS

I am trying to check if an email and an username in a database do already exist. Since I am using mongoose and expressjs I only checked, if the username in a database does already exist, but I need to check the email and username and return a suitable error message for each one. But I don't know how to check them. Here some of code that I wrote so far:

User.findOne({
'username': username
},
function(err, user) {

if (err) {

console.log('Signup error');
return done(err);
}

//if user found.
if (user) {

console.log('Username already exists, username: ' + username);
var err = new Error();
err.status = 310;
return done(err);

}

Answer

use find() function, this may give you perfect result

User.find({ 'username': username,'email':email }, function(err, user) {

        if (err) {

            console.log('Signup error');
            return done(err);
        }

        //if user found.
        if (user.length!=0) {
          if(user[0].username){
            console.log('Username already exists, username: ' + username);                         
             }else{
                console.log('EMAIL already exists, email: ' + email);      
             }                                    
             var err = new Error();
            err.status = 310;
            return done(err);

        }