Search code examples
node.jsmongoosepassport.jsexpress-session

User Id returns as "undefined" when trying to login an user


I'm currently using Node.js along with Mongoose, Express-Session and Passport. This is all to develop the Authentication side of my project.

Today I ran into an issue: When trying to login an user, their Id is undefined. Here is the piece of code that I think is related to this issue:

var User = require("./user-model"); //user model located in another file
var passport = require("passport");
var session = require("express-session");

app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

app.post("/register", (req, res) => {
    var user = new User(req.body);
    user.save()
        .then(item => {
            User.findOne().sort({_id: 1}).exec(function(err, results, fields) {
                if(err) throw err;

                const user_id = results[0]; //Here, the console logs "undefined"

                console.log(results[0]);
                req.login(user_id, function(err) {
                    console.log("User saved to database");
                    res.redirect('/');
                });
            });

        })
        .catch(err => {
            console.log(400).send("Unable to save to database");
        });
});

passport.serializeUser(function(user_id, done) {
  done(null, user_id);
});

passport.deserializeUser(function(user_id, done) {
    done(null, user_id);
});

If you need any extra piece of code, I'll glady update this for you.

Thanks in advance!


Solution

  • findOne finds one result, hence the name.

    So results parameter is in fact user, and it likely should be:

    User.findOne().sort({_id: 1}).exec(function(err, user) {
        if(err) throw err;
    
        const user_id = user._id;
        ...       
    

    Note that user can be null in case there's none.