Search code examples
javascriptnode.jsexpressnpmknex.js

database is not updating despite the db.insert function


I'm making a forgot password functionality in my express app suing node mailer package which sends a new password to the email of the user and then updating the database with the new password but the problem is that the database is not updating with the new password i have reviewed my code many times but unable to figure out the problem.

`app.post('/forgot', (req, res) => {
  const { email } = req.body;
  let newPassword = generatePassword();
  db.select('*').from('login')
  .where('email', '=', email)
  .returning('*')
  .then(user => {
    if (user.length > 0) {
      let mailOptions = {
        from: '[email protected]', 
        to: `${email}`, 
        subject: 'Password reset', 
        html: `<p>Your new password is ${newPassword}</p>`
      };
      transporter.sendMail(mailOptions);
      db('login')
      .where({email: user[0].email})
      .update({
        password: newPassword
      })
      res.json(user[0]);
    } else {
      res.status(404).json('email not found');
    }
  })
});`

Solution

  • You are not calling .then for the second query, so it is built but never ran.

    Also your http returns a value before it knows if update was executed with success.