Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Add data to session in nodejs express in a callback

Add data to session in nodejs express in a callback

Problem

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;
    })
}
Problem courtesy of: shahalpk

Solution

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);
  });
}
Solution courtesy of: kilianc

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Add data to session in nodejs express in a callback

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×