Unable to connect to MongoDB Cluster deployed on MongoDB Cloud using Node.js

Hi Everyone,

I am new to MongoDB and Node.js. I am following the MongoDB documentation and am currently unable to connect to the MongoDB Cluster using Node.js, but it appears to be functioning normally as I am able to establish a connection using the Mongo Shell without any issues.

The following works fine when I run from a terminaL

mongosh "mongodb+srv://my-default-cluster.nopctvg.mongodb.net/" --apiVersion 1 --username sandeepc
Enter password: ***********
Current Mongosh Log ID:	650b432e52a027b381779cdd
Connecting to:		mongodb+srv://<credentials>@my-default-cluster.nopctvg.mongodb.net/?appName=mongosh+2.0.1
Using MongoDB:		6.0.10 (API Version 1)
Using Mongosh:		2.0.1

For mongosh info see: https://docs.mongodb.com/mongodb-shell/
Atlas atlas-cjxqji-shard-0 [primary] test>

However, when I run the following code, it gives me an error. The password enclosed within the parentheses is replaced by the actual password.

Code

const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = "mongodb+srv://sandeepc:<password>@my-default-cluster.nopctvg.mongodb.net/?retryWrites=true&w=majority";

// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
  serverApi: {
    version: ServerApiVersion.v1,
    strict: true,
    deprecationErrors: true,
  }
});

async function run() {
  try {
    // Connect the client to the server	(optional starting in v4.7)
    await client.connect();
    // Send a ping to confirm a successful connection
    await client.db("admin").command({ ping: 1 });
    console.log("Pinged your deployment. You successfully connected to MongoDB!");
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}
run().catch(console.dir);

Error:

/foo/node_modules/mongodb/lib/admin.js:62
            session: options?.session,
                             ^

SyntaxError: Unexpected token '.'
    at wrapSafe (internal/modules/cjs/loader.js:915:16)
    at Module._compile (internal/modules/cjs/loader.js:963:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/media/sandeep/SANDEEP_C/DOCHUB/11_Repositories/01. Github/foo/node_modules/mongodb/lib/index.js:6:17)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)

I just ran npm init followed by npm install mongodb and node connect.js it gave me the above error.

Not sure what am I doing wrong here.

Hello, welcome to the MongoDB community.

I’m not very knowledgeable about nodeJS, but from the examples I saw, they import the client and then you put it as a variable, is it the same thing? Example for finding documents:

import {MongoClient} from "mongodb";

// Replace the uri string with the connection string from your MongoDB deployment.
const uri = "<connection string uri>";

const client = new MongoClient(uri);

asynchronous function run() {
  to try {
    
    // Gets the database and collection on which to perform the operation
    const database = client.db("sample_mflix");
    const movies = database.collection("movies");

    // Query for a film titled 'The Room'
    const query = {title: "The Room"};

    const options = {
      // Sorts matching documents in descending order by rank
      sort: { "imdb.rating": -1 },
      // Includes only the `title` and `imdb` fields in the returned document
      projection: {_id: 0, title: 1, imdb: 1},
    };

    //Run query
    const movie = wait for movies.findOne(query, options);

    // Print the document returned by findOne()
    console.log(movie);
  } finally {
    wait client.close();
  }
}
run().catch(console.dir);

Hi Samuel,

I am using the same code provided here in nodejs-quickstart but it just throws the error mentioned in the original post.

I can connect fine to my cluster from mongo shell using the below, but not from nodejs.

mongosh “mongodb+srv://my-default-cluster.nopctvg.mongodb.net/” --apiVersion 1 --username sandeepc

@Samuel_84194 @Sandeep_Chatterjee

This error is commonly a syntax problem from the driver vs the Node.JS version.

  • Make sure you have the most up to date drivers/node.js versions.
  • Double check for tokens. If your version of Node.JS is less that 14, get it to 14 or chaining isn’t supported.

It’s also possible you’re just using the wrong password…

1 Like

Thank you, Brock. Updating the node version to the latest one v20.7.0 fixed the problem. Cheers. :slight_smile:

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