Unable to connect db because of "throw new MongoParseError('Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"');"

I am the beginner in programming. Please help me out, dear experienced programmers, if you can.
Now I am trying to do a simple To-do app. And I want to use there database. I am stuck for already 12 hours on the stage where it is needed to connect database.
I have the following error after running the command “node index.js”:

throw new MongoParseError('Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"');
                  ^

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

I have the next code in index.js:

const { ApolloServer, gql } = require("apollo-server");

const { MongoClient } = require("mongodb");

const dotenv = require("dotenv");

dotenv.config();

const { DB_URI, DB_NAME } = process.env;

// A schema is a collection of type definitions (hence "typeDefs")

// that together define the "shape" of queries that are executed against

// your data.

const typeDefs = gql`

  # Comments in GraphQL strings (such as this one) start with the hash (#) symbol.

  # This "Book" type defines the queryable fields for every book in our data source.

  type Book {

    title: String

    author: String

  }

  # The "Query" type is special: it lists all of the available queries that

  # clients can execute, along with the return type for each. In this

  # case, the "books" query returns an array of zero or more Books (defined above).

  type Query {

    books: [Book]

  }

`;

const books = [

  {

    title: "The Awakening",

    author: "Kate Chopin",

  },

  {

    title: "City of Glass",

    author: "Paul Auster",

  },

];

// Resolvers define the technique for fetching the types defined in the

// schema. This resolver retrieves books from the "books" array above.

const resolvers = {

  Query: {

    books: () => books,

  },

};

const start = async () => {

  const client = new MongoClient(DB_URI, {

    useNewUrlParser: true,

    useUnifiedTopology: true,

  });

  await client.connect();

  const db = client.db(DB_NAME);

  // The ApolloServer constructor requires two parameters: your schema

  // definition and your set of resolvers.

  const server = new ApolloServer({

    typeDefs,

    resolvers,

    csrfPrevention: true,

    cache: "bounded",

  });

  // The `listen` method launches a web server.

  server.listen().then(({ url }) => {

    console.log(`🚀  Server ready at ${url}`);

  });

};

start();

And the file .env:

DB_URI =

  "mongodb+srv://username:password@cluster0.lghcp.mongodb.net/?retryWrites=true&w=majority";

DB_NAME = Cluster0;

Thank you in advance! :relaxed:

1 Like

Hi @olena_dunamiss welcome to the community!

So a big welcome to the coders club! What I gathered so far is that you’re trying to use Apollo GrapQL to connect to a MongoDB database, to create a todo list app. Is this correct?

Could you provide some more details:

  • What is the tutorial that you’re trying to follow?
  • The error seems to say that DB_URI contains invalid MongoDB URI connection string. Could you insert a console.log(DB_URI) statement somewhere before new MongoClient to verify the content of that variable

If you’re just starting to code, I would suggest you to learn MongoDB in isolation first (without Apollo or GraphQL) by following MongoDB and Node.js Tutorial - CRUD Operations.

Regarding MongoDB + Node, I would also suggest you take a look at the free MongoDB University courses: M001 MongoDB Basics and M220JS MongoDB for JavaScript Developers (although please note that M220JS assumes some familiarity with Javascript/Node).

Best regards
Kevin

Thank you so much for your response and the materials that you added!
The tutorial: Build a GraphQL API with NodeJS and MongoDB (Full-stack MERN Tutorial ) - YouTube
I added console.log(DB_URI) and I have the following:

undefined
C:\Users\Svetl\test\node_modules\mongodb-connection-string-url\lib\index.js:9
    return (connectionString.startsWith('mongodb://') ||
                             ^

TypeError: Cannot read properties of undefined (reading 'startsWith')``
3 Likes

did you install dotenv package, I almost had same error and I found out I need to install dotenv package so I can access to .env variables dotenv in npm registry

1 Like

I had this same issue and I resolved it by simply removing the “;” at the end of the connection string. So you connection string should just be:

"mongodb+srv://username:password@cluster0.lghcp.mongodb.net/?retryWrites=true&w=majority"

That is without the semi-colon at the end.

11 Likes

At this moment, I believe I should just quit my job and become a chef… Thank you, kind sir.

2 Likes

Lol… What are you currently working as btw… thanks Adam!

This was my problem when the mongoose.connect() in my index.js file would not read my process.env. value.

Inside my .env file I had the semi-colon at the end as I usually do when writing JavaScript code:
MONGO_URL=“mongodb+srv:…”;

After removing the semi-colons in my .env files thing were finally working in index.js.

Thank you for this solution.

1 Like

I don’t know if you are still having this problem, but as one other person said you need to remove the semi-colon ( ; ) from your variables in your .env file. That should make the process.env work properly.

2 Likes

WTH!!! Thanks man. Can’t understand coding anymore. 2 full days trying to sort this…

Awesome, I removed the ; from end of line of .env and it’s resolved. Thank you;

Fantastic, I removed the semicolon at the end of the line .env, and the problem is solved. Thank you;

After five long hours of troubleshooting, I see this response. And Guess what happened.

After 14 hours of troubleshooting, I finally found the solution to my problem. I was able to find the solution to my problem by searching the documentation for “connection string”.

See - https://www.mongodb.com/docs/atlas/troubleshoot-connection/#special-characters-in-connection-string-password

1 Like

This solved my problem, too - thank you! Very glad I stumbled upon your solution.

Bruh!!! Thx for help though

Cheers, it worked for me as well.

Hi Guys, does anyone know the reason why it works when semicolon is removed? Also Thank you for the solution @Ubong_Udotai

https://www.npmjs.com/package/dotenv#what-rules-does-the-parsing-engine-follow

From the parsing rules dotenv is preserving the inner quotes, example:

# .env file
URI0="mongodb://foo:solarwinds123@host0,host1,host2/?tls=true"
URI1="mongodb://foo:solarwinds123@host0,host1,host2/?tls=true";
require("dotenv").config()
{
  parsed: {
    URI0: 'mongodb://foo:solarwinds123@host0,host1,host2/?tls=true',
    URI1: '"mongodb://foo:solarwinds123@host0,host1,host2/?tls=true";',
  }
}
1 Like

No dotenv needed ,nothing. Just make sure you do the following:

"ATLAS_URI=“mongodb+srv://…” with NO SPACES .

Yes. It is that easy. Sometimes it might also work if you simply move your config.env from the “server” folder into the root folder of the project.
However, getting rid of whitespaces around “=” is way easier.