0

When I tried to connect the database in this way, it was giving this error, while I have successfully connected the database like this before.

const mongoose = require('mongoose');
require('dotenv').config();

exports.dbConnect = () => {
    mongoose.connect("mongodb://localhost:27017/cloudinaryEntry", {
        useNewUrlParser : true,
        useUnifiedTopology : true,
    })
    .then( () => console.log("Database connected successfully"))
    .catch( (error) => console.log("Error in connected database", error));
}

Here is the code and error

But when I added another attribute "family : 4 " then it get connected successfully. Can someone explain to me why it happened ?

const mongoose = require('mongoose');
require('dotenv').config();
exports.dbConnect = () => {
    mongoose.connect("mongodb://localhost:27017/cloudinaryEntry", {
        useNewUrlParser : true,
        useUnifiedTopology : true,
        family : 4
    })
    .then( () => console.log("Database connected successfully"))
    .catch( (error) => console.log("Error in connected database", error));
}

** Here is the Code

  • Does this answer your question? [Can't connect to MongoDB 6.0 Server locally using Node.js driver](https://stackoverflow.com/questions/74609210/cant-connect-to-mongodb-6-0-server-locally-using-node-js-driver) – Wernfried Domscheit Aug 19 '23 at 10:16

1 Answers1

0

As per the mongoose faq:

The reason why this error happens is that Node.js 18 and up prefer IPv6 addresses over IPv4 by default. And, most Linux and OSX machines have a ::1 localhost entry in /etc/hosts by default. That means that Node.js 18 will assume that localhost means the IPv6 ::1 address. And MongoDB doesn't accept IPv6 connections by default.

The simplist resolution is to just to use 127.0.0.1 instead of localhost in the connection.

The { family: 4 } option you supplied is passed to the Node dns.lookup() function so that IPv4 is used. That's why it allows you to connect.

jQueeny
  • 714
  • 2
  • 13