Using Node.js with MongoDB
This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.
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.
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based Node.js courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for Node.js books — check the publication year so the examples match current versions.
Search Amazon →