Search code examples
node.jsexpresscollectionstokenexpress-jwt

How to update token when the user logs in in express js?


I want to update token in user collection when the user logs in. So far, I have tried this.

router.post("/login", (req, res, next) => {
  User.find({ email: req.body.email })
    .exec()
    .then(user => {
      if (user.length < 1) {
        return res.status(401).json({
          message: "Auth failed"
        });
      }
      bcrypt.compare(req.body.password, user[0].password, (err, result) => {
        if (err) {
          return res.status(401).json({
            message: "Auth failed"
          });
        }
        if (result) {
          const token2 = jwt.sign(
            {
              email: user[0].email,iat: Math.floor(Date.now() / 1000) - 30
            },
            "123",
            {
                expiresIn: "1h"
            }
          );
          User.update({token : token2 })
            .exec()

          return res.status(200).json({
            message: "Auth successful",
            token: token2
          });
        }
        res.status(401).json({
          message: "Auth failed"
        });
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
});

here new token is getting generated but it is not being saved in the user collection. I want to update new token in the collection.

Can anyone know where I am missing?


Solution

  • Try Something like:

    router.post("/login", async (req, res) => {
      try{
        const user = await User.find({ email: req.body.email });
        if (user.length < 1) {
          return res.status(401).json({
            message: "Auth failed"
          });
        }
        bcrypt.compare(req.body.password, user[0].password, (err, result) => {
          if (err) {
            return res.status(401).json({
              message: "Auth failed"
            });
          }
          if (result) {
            const token2 = jwt.sign(
              {
                email: user[0].email,iat: Math.floor(Date.now() / 1000) - 30
              },
              "123",
              {
                expiresIn: "1h"
              }
            );
            User.update({_id:user[0]._id},{$set:{token : token2 }},{new: true});
    
            return res.status(200).json({
              message: "Auth successful",
              token: token2
            });
          }
          res.status(401).json({
            message: "Auth failed"
          });
        });
      }
      catch(err){
        res.status(500).json({
          error: err
        });
      }
    });