Iliyan Yordanov Iliyan Yordanov - 9 months ago 72
Node.js Question

How to check is user already exist with customValidators in express-validator?

I have a problem to return boolean (true or false) if user already exist or not in custom express-validator.
So far I manage to work it in this way:

customValidators: {
isUsernameAvailable: function (username) {
return User
.findOne({ 'username': username })
.then(function (user) {
if (user) {
throw new Error('User already exist')

The idea is to return boolean (corresponding the name: isUsernameAvailable) not Promise or Object, but I don't know how.

I used it to check it in this way:

module.exports = {
create: (req, res) => {
let user = req.body

req.check('username', 'This username is already taken.').isUsernameAvailable()

Answer Source

There's this on the docs: Asynchronous Validation