I am encountering an issue while attempting to establish a connection from my Node.js application to MongoDB using Mongoose. Every time I try to launch the application, I encounter the following error:
"Error connecting to MongoDB: MongooseServerSelectionError: getaddrinfo ENOTFOUND mongodb Below is the code snippet I have implemented for making the connection:
const mongoose = require("mongoose");
require("dotenv").config();
const user = process.env.MONGODB_USER;
const pwd = process.env.MONGODB_PWD;
const host = "mongodb://localhost:27017";
const database = "todoList";
const connectionString = `mongodb://${user}:${pwd}@${host}/${database}`;
mongoose
.connect(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Connected to the database");
})
.catch((err) => {
console.error("Error connecting to the database", err);
process.exit();
});
I have already verified that my MONGODB_USER and MONGODB_PWD environment variables are configured correctly. Additionally, I have confirmed that the MongoDB server is up and running.
Could anyone assist me in identifying what might be causing this connection error and how I can resolve it? Thank you in advance for your help!