shahalpk
shahalpk

Reputation: 3452

Add data to session in nodejs express in a callback

In the below code i'm trying to fetch the user details from DB and save it to session. But unfortunately it doesn't work as i've expected, the data is not written into the session variable. I guess it's because of pass by value? Any workaround


exports.check = function(req,res,next){
    ..
    ..
    getUserFromDB(req);
}

function getUserFromDB(req){
    ..
    db.findOne(query,function(doc){
        req.session.user = doc;
    })
}

Upvotes: 2

Views: 7789

Answers (2)

Oren
Oren

Reputation: 1006

Also check for err, and also for null doc (not found).

Upvotes: 0

kilianc
kilianc

Reputation: 7806

I think you are missing the callback call. Are you using express and mongodb? We should post full working examples :)

exports.check = function (req, res, next) {
  getUserFromDB(req, next);
};

function getUserFromDB(req, callback) {
  db.findOne({ _id: req.qs.id }, function (err, doc) {
    req.session.user = doc;
    callback(err);
  });
}

Upvotes: 4

Related Questions