Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
express-validator with mongoose

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: example@example.com')
    .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: example@example.com')
    .isEmail().isUnique(Model Name);

any suggestions ?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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: example@example.com" ]
    },
    // ...
})
about 4 years ago · Santiago Trujillo Relatório

0

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.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda