Implement Serialization of a Passport User

Tell us what’s happening:
“Database connection is present” test is failing. I know the callback function is not being passed any errors b/c ‘Successful database connection’ is being logged to the console, and the ‘connections’ count for the cluster itself confirms there was a connection. The FCC test confirms the deserializeUser function is also set up properly.

Your code so far

mongo.connect(process.env.DATABASE, {useUnifiedTopology: true, useNewUrlParser: true}, function(err, db){
  if (err) return console.log(err);
  console.log('Successful database connection')
  passport.serializeUser(function(user, done){
    done(null, user._id);
  });
  passport.deserializeUser(function(id, done){
    db.collection('users').findOne({_id: new ObjectID(id)}, function(err, doc){
      if (err) return console.log(err);
      done(null, doc);
    })
  });
});

Link to the glitch project

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36.

Challenge: undefined

Link to the challenge:
https://www.freecodecamp.org/learn/information-security-and-quality-assurance/advanced-node-and-express/implement-the-serialization-of-a-passport-user

1 Like

I figured it out…I had to move app.listen into the connection function:

mongo.connect(process.env.DATABASE, {useUnifiedTopology: true, useNewUrlParser: true}, function(err, db){
  if (err) return console.log(err);
  console.log('Successful database connection')
  passport.serializeUser(function(user, done){
    done(null, user._id);
  });
  passport.deserializeUser(function(id, done){
    db.collection('users').findOne({_id: new ObjectID(id)}, function(err, doc){
      if (err) return console.log(err);
      done(null, doc);
    })
  });

  app.listen(process.env.PORT || 3000, () => {
    console.log("Listening on port " + process.env.PORT);
  });
});
4 Likes