title: nodejs -Expressjs - Cannot set property 'userId' of undefined
body: <p>I'am implementing user authentication using express-session but it is not working. I am getting this error.</p>
  
  <blockquote>
    <p>Cannot set property 'userId' of undefined and throw err; // Rethrow
    non-MySQL errors</p>
  </blockquote>
  
  <p>My routes/user.login code is as follows.  </p>
  
  <pre><code>exports.login = function(req, res){
    var sess = req.session;
     var message = '';
  
     if(req.method == "POST"){
        var post  = req.body;
        var name= post.user_name;
        var pass= post.password;
  
        var sql="SELECT id, first_name, last_name, user_name FROM `users` WHERE `user_name`='"+name+"' and password = '"+pass+"'";
        db.query(sql, function(err, results){
           if(results.length){
              req.session.userId = results[0].id;
              req.session.user = results[0];
              console.log(results[0].id);
              res.redirect('/home/dashboard');
           }
           else{
              message = 'Wrong Credentials.';
              res.render('index.ejs',{message: message});
           }
  
        });
     } else {
        res.render('index.ejs',{message: message});
     }
  
  };
  //-----------------------------------------------dashboard page functionality----------------------------------------------
  
  exports.dashboard = function(req, res, next){
    var sess = req.session;
  
     var user =  req.session.user,
     userId = req.session.userId;
     console.log('ddd='+userId);
     if(userId == null){
        res.redirect("/login");
        return;
     }
  
     var sql="SELECT * FROM `users` WHERE `id`='"+userId+"'";
  
     db.query(sql, function(err, results){
        res.render('dashboard.ejs', {user:user});
     });
  };
  </code></pre>