Node.js Create Connection with MongoDB
MongoDB is a powerful NoSQL database widely used in modern web applications. Combined with Node.js, it provides an efficient way to store, manage, and retrieve data. This guide walks you through creating a clean MongoDB connection from Node.js.
Table of Contents
Install MongoDB
# Linux
sudo apt-get install mongodb
sudo service mongodb start
# Windows: download installer from mongodb.com
Install the MongoDB Driver
npm install mongodb
Connect using async/await
More:- UPDATEGADH
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
const dbName = 'myDatabase';
async function connectDB() {
try {
await client.connect();
console.log('Connected successfully to MongoDB');
const db = client.db(dbName);
// Perform DB operations here
} catch (err) {
console.error('Connection failed:', err);
} finally {
await client.close();
}
}
connectDB();
Connect to MongoDB Atlas (Cloud)
const url = "mongodb+srv://<user>:<password>@cluster.mongodb.net/myDatabase";
Best Practices
- Reuse a single
MongoClientinstance — do not connect per request. - Use environment variables for credentials, never hard-code them.
- Handle connection errors with try/catch.
Download New Real Time Projects:- Click here
Conclusion
Connecting Node.js to MongoDB takes a few lines with the official driver. Reuse a single client, use environment variables, and you are production-ready. For more tutorials, stay tuned.
Keywords
node js connect to mongodb using mongoose, how to connect mongodb with node js in vs code, how to connect mongodb with node js locally, node js mongodb connection example, npm mongodb, connect mongodb with node js express, mongodb nodejs, node js create connection with mongodb w3schools