The session will automatically be saved when the response ends, in this case by res.redirect()
, which is done before the modifications are made to the session.
function(req, res) {
res.redirect('/'); // ends the response, saving the session
populateSession(req, res); // modifies the session without saving
});
Since .findOne()
is asynchronous, if you revise populateSession()
to take and call a callback when the find completes, you can control the order so the session is modified first:
function populateSession(req, res, next) {
User.findOne({
twitterID: req.user.id
}, function(err, result) {
if (result) {
// ...
}
if (next) next(err);
})
}
app.get('/auth/twitter/callback',
/* ... */,
function(req, res) {
populateSession(req, res, function () {
res.redirect('/');
});
});
It also allows you to use populateSession
as middleware:
app.get('/auth/twitter/callback',
/* ... */,
populateSession,
function(req, res) {
res.redirect('/');
});