Reputation: 645
I'm developing my own website using (angularjs, bootstrap) for front end (node, express) for back end (mongodb, mongoose layer) for the database.
I have a registration form and in that form I want to check that the email hasn't already been taken when someone try to create new account, so I want my registration api to check if the submitted email hasn't already been taken before.
I'm now using this validator https://github.com/ctavan/express-validator#validation-by-schema and this is my code :
var vadlidateRegUser= function (req,res,next) {
req.checkQuery('UserName','Username must contain letters and numbers only').isAlphanumeric().notEmpty();
req.checkQuery('Email','Email should have a valid syntax e.g: [email protected]')
.isEmail().notEmpty();
var error = req.validationErrors();
if(!error){
next();
}else {
res.json({success:false, message:error});
}
}
Now I would like to check with the validator if email is unique, something like this:
req.checkQuery('Email','Email should have a valid syntax e.g: [email protected]')
.isEmail().isUnique(Model Name);
any suggestions ?
Upvotes: 3
Views: 7249
Reputation: 51
I know this question is old but i found it today hoping to help me with the same problem but I managed to find a way to do it, so I wanted to share it for the next one to find it.
Now express-validator has the ability to check with Promises.
What I did was to create a seperate file with my mongoose schema and require it in my router, then during my checks i did this:
check('email').custom((value) => {
var query = User.find({ email: value})
return query.exec().then(user => {
if (user.length > 0) {
return Promise.reject('E-mail already in use');
}
});
}),
and everything works like a charm!
I hope this helps someone else. If you need more specifics, just reply so I can add more detail.
Upvotes: 2
Reputation: 5921
express-validator can check and sanitize your input data but can't tell if an email is already in your database.
Best way I think is to make it unique
in your mongoose Schema and handle error when email already exist.:
let User = new Schema({
firstname: String,
lastname: String,
email: {
type: String,
required: true,
unique: true, // ensure unique email
validate: [ isEmail, "Email should have a valid syntax e.g: [email protected]" ]
},
// ...
})
Upvotes: 3