Home > Mobile >  Can't connect to MongoDB 6.0 Server locally using Nodejs driver
Can't connect to MongoDB 6.0 Server locally using Nodejs driver

Time:11-29

I have just started learning about MongoDB and I am trying to host my node js application locally via MongoDB Server 6.0 (without using mongoose or atlas)

I copied the async javascript code given in the MongoDB docs. I made sure to run mongod before executing the below code MongoDB server started

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

// Connection URI
const uri =
  "**mongodb://localhost:27017**";

// Create a new MongoClient
const client = new MongoClient(uri);

async function run() {
  try {
    // Connect the client to the server (optional starting in v4.7)
    await client.connect();

    // Establish and verify connection
    await client.db("admin").command({ ping: 1 });
    console.log("Connected successfully to server");
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}
run().catch(console.dir);

It's throwing an error: image of the error it's throwing

CodePudding user response:

Problem is, the localhost alias resolves to IPv6 address ::1 instead of 127.0.0.1

However, net.ipv6 defaults to false.

The best option would be to start the MongoDB with this configuration:

net:
  ipv6: true
  bindIpAll: true

or

net:
  ipv6: true
  bindIp: localhost

Then all variants should work:

C:\>mongosh "mongodb://localhost:27017?authSource=admin" --quiet --eval "db.getMongo()"
mongodb://localhost:27017/?authSource=admin&directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh 1.6.0

C:\>mongosh "mongodb://127.0.0.1:27017?authSource=admin" --quiet --eval "db.getMongo()"
mongodb://127.0.0.1:27017/?authSource=admin&directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh 1.6.0

C:\>mongosh "mongodb://[::1]:27017?authSource=admin" --quiet --eval "db.getMongo()"
mongodb://[::1]:27017/?authSource=admin&directConnection=true&appName=mongosh 1.6.0
  • Related