intermediate#Node.js#MongoDB
Using Node.js with MongoDB
Learn how to use Node.js with MongoDB to create a simple CRUD application.
Introduction to MongoDB
MongoDB is a popular NoSQL database that allows you to store data in a flexible and scalable way.
Step 1: Install MongoDB
Install MongoDB on your computer and start the MongoDB server.
brew install mongodb
mongod
Step 2: Install the MongoDB Driver
Install the MongoDB driver for Node.js.
npm install mongodb
Step 3: Connect to MongoDB
Connect to the MongoDB server using the mongodb package.
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
MongoClient.connect(url, (err, client) => {
if (err) {
console.log(err);
} else {
console.log('Connected to MongoDB');
}
});
Step 4: Create a Collection
Create a new collection in the MongoDB database.
const db = client.db();
const collection = db.collection('users');
Step 5: Perform CRUD Operations
Perform CRUD operations on the collection.
// Create a new document
const user = { name: 'John Doe', age: 30 };
collection.insertOne(user, (err, result) => {
if (err) {
console.log(err);
} else {
console.log('Document inserted');
}
});
Run the code to see the MongoDB application in action.