Categories
JavaScript Answers

How to fix ECONNREFUSED error when connecting to MongoDB from Node.js?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.