check if the email already exists

Asked

Viewed 991 times

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.

2 answers

0


not complicating the code, what is just forgetting, is that the connection to the database is given in an asyncronous way, IE, do not know if it takes 1ms or 3s to receive the answer, but, by the code it presents, expects the answer is syncrona.

I just used a function:

const isValidEmail = (email, cb) => {
    const reg = new RegExp(/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/);
    if (!reg.test(email)) {
        // nao é um email valido, nao vale a pena perguntar se existe na DB
        cb(new Error('RegEx: Email nao é valido'));
        return;
    }

    mongodb.connect((err, db) => {
        db.collection('users').findOne({email: value}, (err, res) => {
            if (res && res.email === value) { 
                // email existe na base de dados
                cb(new Error('DB: Email existente'));
            } else {
                cb(null); // OK
            }
        })
    });    
}

and in its function, only:

app.post('/users/', (req, res) => {

    const email = req.body.email;
    isValidEmail(email, (err) => {
        if(err) {
            res.status(400).send(err.message);
        } else {
            res.status(200);
        }
    });
}
  • Thanks guy a little while ago I started studying Ode.js and still learning about "asyncronity"

0

The answer above is a little more "clean", but if you want to continue with your logic the problem is in the following code:

app.post('/users/', async(req, res, next) => {
      let contract = new validationContract()
      await contract.exists(req.body.email) //<- exists troque por isValidEmail
      if (!contract.isValid()) {
        res.status(400).send(contract.errors()).end()
        return
      }
    }

You linked Function to the prototype but called something that was not defined

  • The mistake there was mine, actually when I posted the question here had already fixed the name of Function in my code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.