javascript - Add data to session in nodejs express in a callback - Stack Overflow

In the below code i'm trying to fetch the user details from DB and save it to session. But unfortu

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;
    })
}

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;
    })
}
Share Improve this question edited Oct 10, 2015 at 22:21 David Jones 4,3057 gold badges30 silver badges51 bronze badges asked Jul 1, 2012 at 10:18 shahalpkshahalpk 3,4627 gold badges39 silver badges56 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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);
  });
}

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745076327a4609858.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信