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.