Unable to connect to database-MongoParseError: URI malformed, cannot be parsed

Tell us what’s happening:
Describe your issue in detail here.
I m getting the below error ,can anyone please tell me what i am missing here.

Your code so far

server.js code

'use strict';
require('dotenv').config();
const express = require('express');
const myDB = require('./connection');
const fccTesting = require('./freeCodeCamp/fcctesting.js');
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 }));

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

Console:

MongoParseError: URI malformed, cannot be parsed
    at parseConnectionString (/home/runner/boilerplate-advancednode-7/node_modules/mongodb/lib/core/uri_parser.js:560:21)
    at connect (/home/runner/boilerplate-advancednode-7/node_modules/mongodb/lib/operations/connect.js:282:3)
    at /home/runner/boilerplate-advancednode-7/node_modules/mongodb/lib/mongo_client.js:223:5
    at maybePromise (/home/runner/boilerplate-advancednode-7/node_modules/mongodb/lib/utils.js:662:3)
    at MongoClient.connect (/home/runner/boilerplate-advancednode-7/node_modules/mongodb/lib/mongo_client.js:219:10)
    at main (/home/runner/boilerplate-advancednode-7/connection.js:11:22)
    at Object.<anonymous> (/home/runner/boilerplate-advancednode-7/server.js:17:1)

Your browser information:

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

Challenge: Implement the Serialization of a Passport User

Link to the challenge:

If you are using replit did you add the DB connection string to the secrets. It is being used in connection.js. Or if using some other platform it would go in the .env file.

2 Likes

Hey,It worked after adding database string to the secrets. Thank you.

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