Reputation: 125
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);
}
});
Upvotes: 0
Views: 1372
Reputation: 2636
You can simply use the user objet which is found.
User.findOne({
$or: [ { 'username': req.body.username}, {'email': req.body.email}]
}, function(err, user) {
if (user) {
if(user.username == req.body.username){
console.log('username is taken');
}else{
console.log(' email is taken');
}
} else {
userDetails.save(function(err) {
if (err) throw err;
});
}
if (err) {
return done(err);
}
});
Upvotes: 0
Reputation: 4625
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();
});
});
Upvotes: 2