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:
import dotenv from "dotenv";
dotenv.config({
path: "./env",
});
"scripts": {
"dev": "nodemon -r dotenv/config --experimental-json-modules src/index.js",
},
8. Database Connection:
import dotenv from "dotenv";
import connectDB from "./db/index.js";
dotenv.config({
path: "./env",
});
connectDB();