Implement the Serialization of a Passport User

Hi, where is something wrong?

'use strict';
require('dotenv').config();
const express = require('express');
const myDB = require('./connection');
const fccTesting = require('./freeCodeCamp/fcctesting.js');
const pug = require('pug');
const passport = require('passport');
const session = require('express-session')
const { ObjectID } = require('mongodb');
const mongo = require('mongodb').MongoClient;
const mySecret = process.env['MONGO_URI']


const app = express();
app.set('view engine', 'pug');
app.set('views', './views/pug');

app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: true,
  saveUninitialized: true,
  cookie: { secure: false }
}));

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

passport.serializeUser((user, done) => {
  done(null, user._id);
});

myDB(async (client) => {
  const myDataBase = await client.db('database').collection('users');

  // Be sure to change the title
  app.route('/').get((req, res) => {
    // Change the response to render the Pug template
    res.render('pug', {
      title: 'Connected to Database',
      message: 'Please login'
    });
  });

  // Serialization and deserialization here...
  passport.serializeUser((user, done) => {
    done(null, user._id);
  });
  passport.deserializeUser((id, done) => {
    myDataBase.findOne({ _id: new ObjectID(id) }, (err, doc) => {
      done(null, doc);
    });
  });
  // Be sure to add this...
}).catch((e) => {

app.route('/').get((req, res) => {
  res.render('pug', { title: e, message: 'Unable to login' });
});
});

fccTesting(app); //For FCC testing purposes
app.use('/public', express.static(process.cwd() + '/public'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
   
app.route('/')
      .get((req, res) => {
      res.render('index', { title: 'Hello', message: 'Please log in' });
    });   
    
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log('Listening on port ' + PORT);
});

with this error:

Database connection should be present.

Hello!

Can you provide your code on repl.it or github so we can see it all?

Note: remember to remove any private information, like database credentials, emails, etc.

here is the repl:

Comment out the routes you added after the myDB function and change the render(s) to use index not pug

Not sure why you have added the code you have after the myDB function.

3 Likes

Thanks you very much for the help.
sorry I was lost, restarted the project and is fixed.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.