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:

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