最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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).

发布评论

评论列表(0)

  1. 暂无评论