How to Connect Node.js with MongoDB?
Ad
How to Connect Node.js with MongoDB
Learn how to establish a connection between Node.js and MongoDB using the official MongoDB driver or Mongoose ODM.
Installation
npm install mongodb
# or using Mongoose
npm install mongooseBasic Connection (Native Driver)
const { MongoClient } = require('mongodb');
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
async function connect() {
try {
await client.connect();
console.log("Connected to MongoDB");
const database = client.db('myDatabase');
const collection = database.collection('users');
return collection;
} catch (error) {
console.error(error);
}
}Using Mongoose
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/myDatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Connection error', err));Best Practices
- Use environment variables for connection strings
- Implement connection pooling
- Handle errors properly
- Close connections when done
