John Anderson John Anderson - 3 months ago 19
Node.js Question

Using the Mongoose $or operator

How I can tell whether the username or the email in this scenario was the one that was found in the mongo database. I use

$or: [ { 'username': req.body.username}, {'email': req.body.email}]
to find an existing username or email but I need to know which one was found so I can send a message to the client to say the username is taken or the email is taken. I tried to log the "user" variable but it returned the object were it found the match.

User.findOne({
$or: [ { 'username': req.body.username}, {'email': req.body.email}]
}, function(err, user) {
if (user) {
console.log('username or password is taken');
} else {
userDetails.save(function(err) {
if (err) throw err;
});
}
if (err) {
return done(err);
}
});

Answer

How about using pre validate hooks for validating unique email and username.

User.pre('validate', true, function validateUniqueEmail( next, done) {
    next(); 
    User.findOne({email: this.email}).exec(function(err, user) {


    if(err) {
    return done(err);
    }

    if(user) {

    return done(new Error('Email is taken'));
    }

    done();

    });


});


User.pre('validate', true, function validateUniqueUsername( next, done) {
    next();
    User.findOne({username: this.username}).exec(function(err, user) {


    if(err) {
    return done(err);
    }

    if(user) {

    return done(new Error('Username is taken'));
    }

    done();

    });


});