How to Connect a Database in a MERN Stack
Professionally Connect a Database in a MERN Stack
Step 1: Get the MongoDB URL from MongoDB Atlas
Log into MongoDB Atlas: Go to MongoDB Atlas and log into your account.
Select Your Cluster: Navigate to the cluster you want to connect to.
Connect: Click the "Connect" button for your cluster.
Choose a Connection Method: Select "Connect your application".
Copy the Connection String: You will see a connection string that looks like this:
phpCopy codemongodb+srv://<username>:<password>@cluster0.mongodb.net/<dbname>?retryWrites=true&w=majority
Replace
<username>
and<password>
with your database user credentials.Replace
<dbname>
with the name of the database you want to connect to.
Step 2: Export the Database Name in the Constants Folder
Create or Open the Constants File: In your project's
constants
folder, open or create a file namedindex.js
.Export the Database Name: Inside
index.js
, export theDB_NAME
variable.javascriptCopy codeexport const DB_NAME = 'your_database_name';
- Replace
'your_database_name'
with the actual name of your MongoDB database.
- Replace
By exporting the DB_NAME
variable from the constants folder, you ensure that the database name is defined in one central location and can be easily accessed and updated throughout your application. This promotes maintainability and consistency in your codebase.
Step 3: Create index.js
in the DB Folder
- Create or Open the
index.js
File: Inside your project'sdb
folder, create a file namedindex.js
.
Write the Connection Code: In index.js
, write the code to establish the MongoDB connection using Mongoose. You can use the mongoose.connect()
function along with the database name exported from the constants folder.
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(`mongo db connected!! DB Host:${connectioninstance.connection.host}`);
} catch (error) {
console.log("MONGODB CONNECTION ERROR",error);
process.exit(1);
}
}
export default connectDB
Creating an index.js
file in the db
folder allows you to encapsulate database connectivity logic in a single module. This promotes code organization and modularity, making it easier to maintain and understand your application's database-related code.
Step 4: Import index.js
from the DB Folder and Configure dotenv
Import
index.js
from the DB Folder: Import theindex.js
file from thedb
folder to establish the database connection.Import and Configure
dotenv
: Import thedotenv
package and call theconfig()
method to load environment variables from the.env
file.for importing dotenv add this in script in pakage .jason file
"scripts": { "dev": "nodemon -r dotenv/config --experimental-json-modules src/index.js" },