Unable to Connect to Database (in Advanced Node and Express -> Implement the Serialization)

Having problems in completing the challenge. Encountering Error:

//------------------------------------------------------------------

MongoParseError: URI malformed, cannot be parsed
at parseConnectionString (/home/runner/boilerplate-advancednode/node_modules/mongodb/lib/core/uri_parser.js:580:21)
at connect (/home/runner/boilerplate-advancednode/node_modules/mongodb/lib/operations/connect.js:283:3)
at /home/runner/boilerplate-advancednode/node_modules/mongodb/lib/mongo_client.js:284:5
at maybePromise (/home/runner/boilerplate-advancednode/node_modules/mongodb/lib/utils.js:692:3)
at MongoClient.connect (/home/runner/boilerplate-advancednode/node_modules/mongodb/lib/mongo_client.js:280:10)
at main (/home/runner/boilerplate-advancednode/connection.js:12:22)
at Object. (/home/runner/boilerplate-advancednode/server.js:28:1)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions…js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
/home/runner/boilerplate-advancednode/connection.js:20
throw new Error(‘Unable to Connect to Database’)
^

Error: Unable to Connect to Database
at main (/home/runner/boilerplate-advancednode/connection.js:20:15)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

//------------------------------------------------------------------

Server.js

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

const app = express();
const session = require('express-session')
const passport = require('passport')
const { ObjectID } = require('mongodb');

app.set('view engine', 'pug');
app.set('views', './views/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 => {
  // wait for the db connection
  const myDataBase = await client.db('Cluster0').collection('users')

  // response to render the Pug template
  // (app.route - chain multiple HTTP methods for a single route)
  app.route('/')
    .get((req, res) => {
      res.render('index', { title: 'Hello', message: 'Please log in' })
    });
  
  // serialize & de
  passport.serializeUser((user, done) => {
    done(null, user._id);
  });
  passport.deserializeUser((id, done) => {
    myDataBase.findOne({ _id: new ObjectID(id) }, (err, doc) => {
      done(null, doc);
    });
  });
})


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

connection.js

// Do not change this file
require('dotenv').config();
const { MongoClient } = require('mongodb');
const mySecret = process.env['MONGO_URL'];

async function main(callback) {
    const URI = mySecret; // Declare MONGO_URI in your .env file
    const client = new MongoClient(URI, { useNewUrlParser: true, useUnifiedTopology: true });

    try {
        // Connect to the MongoDB cluster
        await client.connect();

        // Make the appropriate DB calls
        await callback(client);

    } catch (e) {
        // Catch any errors
        console.error(e);
        throw new Error('Unable to Connect to Database')
    }
}

module.exports = main;

Could anyone help in identifying the issue ?

Have you declared MONGO_URI or MONGO_URL in your environment variables?

1 Like

I’m working in replit - and as I understand, the basic version no longer supports environment variables. So I declared them as secrets (MONGO_URL and SECRET_KEY)

Yes, that’s right. So it’s working now?

they have been declared before

Why have you declared two env variables? You should have one (usually something like MONGO_URI in this case) which holds the url which you use to connect to your database.

as I understood - MONGO_URI was for db connection, SECRET_KEY for authentication. (I meant SESSION_SECRET)

Oh right. Have you checked that your MONGO_URL is in the correct format?

mongodb+srv://<username>:<password>@<cluster-name>.prx1c.mongodb.net/<db-name>?retryWrites=true&w=majority
1 Like

think I know whats wrong . stupid mistake - but reading your response helped me catch it. in connection.js I declared const mySecret = process.env['MONGO_URL']; but in secrets it was declared as MONGO_URI . ive changed it - error gone

still cant pass the : Database connection should be present. test. :face_with_diagonal_mouth:

title: ‘Connected to Database’ :+1: pass. thx for your time brotha