Advanced Node & Express - Database connection

Tell us what’s happening:
I have trouble trying to pass, Implement the Serialization of a Passport User.
I need help to pass the Database connection should be present.

I am able to pass the second test,

Deserialization should now be correctly using the DB and done(null, null) should be called with the doc .

But for some reason, I cannot pass the first test,

Database connection should be present.

  • What is wrong in my replit code that does not allow the database connection?
  • Is there an error in the server.js file or in the sample.env file?
  • Where should I fix in my replit code? Is it in the package.json file, sample.env file, server.js file or the connection.js file?
  • I added my MONGO_URI code into the sample.env file. I rather not show it containing my password…
PORT=8080
NODE_ENV=development
SESSION_SECRET="tryagaincoding"
MONGO_URI="my mongodb code"

Your code so far

'use strict';
require('dotenv').config();
const express = require('express');
const myDB = require('./connection');
const fccTesting = require('./freeCodeCamp/fcctesting.js');
const session = require('express-session');
const passport = require('passport');
const ObjectID = require('mongodb').ObjectID;

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

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.use(session({
  secret: process.env.SESSION_SECRET,
  resave: true,
  saveUninitialized: true,
  cookie: { secure: false }
}));

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

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' });
  });
});
// app.listen out here...

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

My link to my Replit:

https://replit.com/@ArtC/boilerplate-advancednode-2#server.js

I appreciate the help. :slight_smile:

Your browser information:

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

Challenge: Implement the Serialization of a Passport User

Link to the challenge:

SESSION_SECRET and MONGO_URI does not need any “quote”.

Ok, I have removed the quote marks from both SESSION_SECRET and MONGO_URI. But it is still not passing the Database Connection test.

Both SESSION_SECRET and MONGO_URI are supposed to be in the sample.env file already in the replit, right? Or do I have to make my own ,env file?

Is there something wrong with my MONGO_URI?

No. sample.env is just sample, for other people who download your app to create their own .env.
If you’re using replit, click the padlock icon on the left-bar, and fill in the key value pair.
We create .env if we write on our own vscode and use github for version control.

Ok. I did the padlock icon on the left-bar. I added my MONGO_URI & its key value pair.

Where should I add my code const mySecret = process.env['MONGO_URI'] in the server.js file?

I am still not passing the Database connection test.

follow the example in the given link or fall back to the back end dev certification, the unit about use the .env file

I do not understand what you mean. I put in my MONGO_URI & its key value in the padlock icon on the left-bar. After I pressed enter, it gave me the code, const mySecret to insert.

I tried to add the const mySecret = process.env['MONGO_URI'] in the server.js file.
I added it underneath the other const codes. Did I place my const mySecret code in the correct line?

'use strict';
require('dotenv').config();
const express = require('express');
const myDB = require('./connection');
const fccTesting = require('./freeCodeCamp/fcctesting.js');
const session = require('express-session');
const passport = require('passport');
const ObjectID = require('mongodb').ObjectID;

// Add my MONGO_URI
const mySecret = process.env['MONGO_URI']

I put in the SESSION_SECRET and MONGO_URI in the sample.env file. The sample.env file alread had the MONGO_URI=''. Was I suppose to put in my MONGO_URI code in there? I removed the quotation marks for the SESSION_SECRET and MONGO_URI like you mentioned. Did I have to make my own separate.env file for my MONGO_URI?

PORT=8080
NODE_ENV=development
SESSION_SECRET= randomcoder
MONGO_URI= mongodb+srv-(I do not want to show my password)

I see this error message in the Replit console:

MongoError: bad auth : Authentication failed.
    at MessageStream.messageHandler (/home/runner/boilerplate-advancednode-1/node_modules/mongodb/lib/cmap/connection.js:268:20)
    at MessageStream.emit (events.js:315:20)
    at processIncomingData (/home/runner/boilerplate-advancednode-1/node_modules/mongodb/lib/cmap/message_stream.js:144:12)
    at MessageStream._write (/home/runner/boilerplate-advancednode-1/node_modules/mongodb/lib/cmap/message_stream.js:42:5)

What error am I doing that does not allow the Database connection to pass? Does the main coding take place in the server.js file or somewhere else in Replit?

I try to work on new different Replits in order to find out the proper way to add the codes correctly in order. This is my new replit link.
My Replit link: https://replit.com/@ArtC/boilerplate-advancednode-1#server.js

There’s suppose to be no space for any code lines in .env file, or mysecret.

You don’t need to do anything on sample.env. I don’t think the spec is checking it at all. Its purpose is only to show other people what key=value are supposed to be defined in the real .env that they’re suppose to create for themselves using their own private confidential values if they downloaded your app. So, logically, what we have to do with sample.env is just copy pasting whatever in our .env file, then replace all the values with some dummy values.

I tried copy pasting your code to my replit to play around, yet no matter how I tweaked it to give an error, it kept giving a pass, so I can’t narrow down the scope of probable problem.

Have you replaced “myFirstDatabase” in mongo uri to your own database name though?

I don’t see any problem defining the mySecret variable at that spot.

Where can I find this “myFirstDatabase” in MONGO_URI?
Is it in Replit, like somewhere I missed?
Does it have to do with my MongoDB Atlas?
I have already got my MONGO_URI in the sample.env file. Are you saying I do have to make my own .env file of my own in Replit?

What about my const mySecret = process.env['MONGO_URI']? Did I place it in the server.js properly?

Do not touch sample.env. It does not matter anyway. You can even delete it now.

You are suppose to change the password and database name in the string given by MongoDB before assigning it to MONGO_URI in the padlock icon.

mongodb+srv://audrey-coder-practice:fccmongooseea@audreycoderpractice.snhgf.mongodb.net/myFirstDatabase?retryWrites=true&w=majority

Oh, ok I see. I forgot to change the “myFirstDatabase” in the mongo_uri. But when I did that & also made my own “session.env” file, I was able to run the replit & receive the console result,

express-session deprecated req.secret; provide secret option server.js:21:9
Listening on port undefined
https://www.freecodecamp.org
Error: secret option required for sessions

I am still doing something wrong that still does not let the Database connection pass. I almost feel close to just pass this test. I appreciate your help.

I have inserted the const mySecret = process.env['MONGO_URI'] in the server.js file. What else am I doing wrong?

secret: process.env.SESSION_SECRET

looks for SESSION_SECRET in the padlock. Have you defined it?

input whatever random value you want. It basically works as a “salt” to complicate the encryption (hashing-rehashing).

I finally got it to pass. I see that I needed to add the SESSION_SECRET in the secret variables like the MONGO_URI. I thought I needed to add the insert code const mySecret = process.env['SESSION_SECRET'] into the server.js file, just like the const mySecret = process.env['MONGO_URI']. But it turns out I do not need to since there is a code already, secret: process.env.SESSION_SECRET.

OMG, thank you so much!

This mod is sketchy. I’m still stuck at 20, retyping whatever in the examples, and still have no clues what to type and where to type it either in auth.js, routes.js or server.js. If you want to bail, now is still a good time. lol