I'm using the express-session package and I want to change the variable "_id" in the session. Here my session init
app.use(session({
secret: "secretshhhhhh",
resave: true,
saveUninitialized: false,
}))
After the login page I try to store the id with these few lines:
req.session._id = user._id.toString()
req.session.save(function (err) {
req.session.save(function (err) {
console.log(req.session)
})
})
The console.log print the session with the id, but when I try to get the _id in an other page express send me back a null object. Here an exemple of printing session without the _id
return res.status(200).send(req.session);
I tried many methods but none of these worked for me.
EDIT: Here my whole function to put it in session
module.exports.login_post = async function (req, res) {
User.findOne({ email: req.body.email }, function (err, user) {
if (user == null) {
return res.status(400).send({
message: "User not found"
})
}
else {
if (user.validPassword(req.body.password)) {
req.session._id = user._id.toString()
req.session.save(function (saveErr) {
req.session.reload(function (reloadSave) {
console.log(req.session, saveErr, reloadSave)
})
})
}
}
})
}
Here my whole function to get it from session
module.exports.session_get = function(req, res) {
return res.status(200).send(req.session);
}
module.exports.session_destroy = function(req, res) {
req.session.destroy();
return res.status(200).send({
message: "Session detroyed"
});
}