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?