2

Using Express and Mongoose I have the below code which finds a user, checks the username then matches the password.

/* POST signin with user credentials. */
router.post('/signin', async (req, res, next) => {
  let result = await User.find({
    email: req.body.email
  });

  let user = result[0];
  bcrypt.compare(req.body.password, result[0].password, (err, result) => {
    if (result) {
      user._doc.token = jwt.sign({
        email: req.body.email
      }, config.secret, {
        expiresIn: 86400,
      });
      res.send(user);
    } else {
      res.status(401).send({
        message: 'Password does not match.'
      });
    }
  });
});

When the JWT token is signed I want to add the token key val to the user object and return it.

But after lots of trial and error I was unable to do user.token =jwt.sign and I have to do user._doc.token = jwt.sign.

Being new to Mongoose and MongoDB, is this the only way I can add to a returned document that I want to assign to a variable to and make it mutable?

1 Answers1

0

Try using .toObject() on your user document to get a plain javascript object, in which you can operate as you like.

The code

let user = result[0].toObject();

should return you the plain user object, then you can make user.token = jwt.sign.

For reference, see http://mongoosejs.com/docs/api.html#document_Document-toObject

Andre Knob
  • 821
  • 7
  • 7