To fix ECONNREFUSED error when connecting to MongoDB from Node.js, we call connect.
For instance, we write
const mongoose = require("mongoose");
const mongoURI = "mongodb://localhost:27017/test";
const MongoDB = mongoose.connect(mongoURI).connection;
MongoDB.on("error", (err) => {
console.log(err.message);
});
MongoDB.once("open", () => {
console.log("mongodb connection open");
});
to call connect to connect to MongoDB with the mongoURI.
We get the connection with the connection property.
And we call on to catch errors.
We call once to catch the first emission of the open event.