Establishing MongoDB Connection in a Node.js Application using Mongoose

Establishing MongoDB Connection in a Node.js Application using Mongoose

1. Importing Dependencies:

The code begins by importing the necessary dependencies. mongoose is a popular Object Data Modeling (ODM) library for MongoDB and is widely used with Node.js applications. Additionally, it imports the constant DB_NAME from an external file, presumably containing the name of the MongoDB database.

import mongoose from "mongoose";
import { DB_NAME } from "../constants.js";        

2. Connection Function: The connectDB function is defined with the async keyword, indicating it will work with promises. This function is responsible for establishing a connection to the MongoDB database.

const connectDB = async () => {
  // Code for database connection
};        

3. Database Connection: Inside the try block, the mongoose.connect method is used to connect to the MongoDB database. The connection string is constructed using the MONGODB_URI environment variable and the DB_NAME constant.

const connectionInstance = await mongoose.connect(
  `${process.env.MONGODB_URI}/${DB_NAME}`
);        

4. Logging Connection Details: If the connection is successful, the code logs a message to the console, indicating that the connection to MongoDB has been established. It also displays the host information from the connection instance.

console.log(
  `\n MongoDB Connected !! DB HOST: ${connectionInstance.connection.host}`
);        

5. Handling Connection Errors: In case of any errors during the connection process, the catch block is triggered. An error message is logged to the console, and the application exits with a status code of 1.

} catch (error) {
  console.log("MONGODB connection failed:", error);
  process.exit(1);
}        

6. Exporting the Function: Finally, the connectDB function is exported as the default export, making it available for use in other parts of the application.

export default connectDB;        

Full Code of connectDB:

import mongoose from "mongoose";
import { DB_NAME } from "../constants.js";

const connectDB = async () => {
  try {
    const connectionInstance = await mongoose.connect(
      `${process.env.MONGODB_URI}/${DB_NAME}`
    );
    console.log(
      `\n MongoDB Connected !! DB HOST: ${connectionInstance.connection.host}`
    );
  } catch (error) {
    console.log("MONGODB connection failed:", error);
    process.exit(1);
  }
};

export default connectDB;
        

7. Environment Variable Configuration:

  • The dotenv package is imported to handle the configuration of environment variables.
  • The dotenv.config() method is used to load the environment variables from a file, typically named .env. In this case, the path option is set to "./env", specifying the directory where the environment variable file is located.

import dotenv from "dotenv";

dotenv.config({
  path: "./env",
});        

  • Here to import dotenv like this we have to modify the package.json, we have to modify scripts as:

 "scripts": {
    "dev": "nodemon -r dotenv/config --experimental-json-modules src/index.js",
  },        

8. Database Connection:

  • The connectDB function, imported from the db module (presumably containing the MongoDB connection logic), is invoked.

import dotenv from "dotenv";

import connectDB from "./db/index.js";

dotenv.config({
  path: "./env",
});

connectDB();        

要查看或添加评论,请登录

Suraj Pathak的更多文章

社区洞察

其他会员也浏览了