MongoParseError: Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"

Not able to connect to Mongo DB Atlas Database when using mongoose.connect.

Error –

MongoParseError: Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"

Code –

import mongoose from "mongoose";
import { DB_NAME } from "../constants.js";

const connectDB = async () => {
  try {
    const connectionInstance = await mongoose.connect(
      `${process.env.MONGODB_URI}/${DB_NAME}`
    );
    console.log(`MONGODB CONNECTED !! ${connectionInstance.connection.host}`);
  } catch (error) {
    console.error(error);
  }
};

export default connectDB;

And here is my .env file –

PORT = 8000
MONGODB_URL = mongodb+srv://sumit:xxx@cluster0.fgkpmta.mongodb.net/

Please help

Hey @Sumit_Rajak,

Welcome to the MongoDB Community forums :sparkles:

It seems like there might be a couple of issues in your code and configuration.

  • In the Connection String in .env File - You’ve defined MONGODB_URL , but in your code, you’re trying to use process.env.MONGODB_URI. Make sure these match.

  • Apart from that there is no declaration of the DB_NAME in your .env file. Also, I’ll recommend to concatenate the URL string properly. For example: use backticks (`) for string interpolation, not quotes.

Here is the formatted code snippet for your reference:

import mongoose from "mongoose";
import { DB_NAME } from "../constants.js";
require("dotenv").config(); // Ensure .env file is read

const connectDB = async () => {
  try {
    const connectionInstance = await mongoose.connect(
      `${process.env.MONGODB_URL}/${DB_NAME}`, // Use process.env.MONGODB_URL
    );
    console.log(`MONGODB CONNECTED !! ${connectionInstance.connection.host}`);
  } catch (error) {
    console.error(error);
  }
};

export default connectDB;

I hope it helps!

Best regards,
Kushagra

2 Likes

Hello,

I modified and changed the MONGODB_URL in my .env to MONGODB_URI.

Still getting the same error.

Here is my code –

import mongoose from “mongoose”;
import { DB_NAME } from “…/constants.js”;
import dotenv from “dotenv”;

dotenv.config({
path: “/.env”,
});

const connectDB = async () => {
try {
const connectionInstance = await mongoose.connect(
${process.env.MONGODB_URI}/${DB_NAME}, // Use process.env.MONGODB_URL
);
console.log(MONGODB CONNECTED !! ${connectionInstance.connection.host});
} catch (error) {
console.error(error);
}
};

export default connectDB;

1 Like

Hello,

I have fixed the error.

The error was my .env file was not loading cause i gave the wrong path.

Thank you so much for the help.

1 Like