0
I created this function to check if an email already exists in DB
let errors = [];
function ValidationContract() {
errors = [];
}
// verifica a validade do email e se o mesmo ja existe no banco
ValidationContract.prototype.isValidEmail = (value) => {
const reg = new RegExp(/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/);
if (!reg.test(value)) { errors.push({message: messageEmailInvalid}) }
mongodb.connect((err, db) => {
db.collection('users').findOne({email: value}, (err, res) => {
if (res && res.email === value) { errors.push({ message: messageEmailExist }) }
})
});
}
ValidationContract.prototype.errors = () => {
return errors;
}
ValidationContract.prototype.isValid = () => {
return errors.length == 0;
}
but when I apply it to the route it just doesn’t work
app.post('/users/', async(req, res, next) => {
let contract = new validationContract()
await contract.isValidEmail(req.body.email)
if (!contract.isValid()) {
res.status(400).send(contract.errors()).end()
return
}
}
Can anyone explain to me where I’m going wrong or what I’m forgetting
It won’t work because you don’t know when you get the error from the database, you have to wait and only proceed when you know the answer (async), for this purpose you have to use promises (or callback). the method
isValid()
is not waiting for the response from the database.– balexandre