Connecting Node.js to MongoDB
To use MongoDB with Node.js, follow these steps:
1. Install MongoDB Driver or Mongoose
Install Mongoose, a popular ODM library, for easy interaction with MongoDB
npm install mongoose
2. Set Up MongoDB Connection
Connect your Node.js application to a MongoDB database.
Example Code:
const mongoose = require('mongoose');
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('Connected to MongoDB'))
.catch((err) => console.error('Connection error:', err));