If you are a web developer looking to build a Node.js application that requires database functionality, MongoDB is a popular choice. MongoDB is a NoSQL database that stores data in JSON-like documents, making it a flexible and scalable option for modern web applications.
In this tutorial, we will walk through the basic CRUD (Create, Read, Update, Delete) operations in MongoDB using Node.js. We will cover how to connect to a MongoDB database, create documents, retrieve documents, update documents, and delete documents.
Prerequisites
Before we dive into the tutorial, make sure you have the following installed:
- Node.js (version 10 or higher)
- MongoDB (version 4.0 or higher)
You will also need to have a basic understanding of JavaScript and Node.js.
Step 1: Set Up a MongoDB Database
First, let's set up a MongoDB database. Open a terminal and start the MongoDB server by running the following command:
mongod
Next, open another terminal window and run the following command to connect to the MongoDB shell:
mongo
Now that we are in the MongoDB shell, let's create a new database:
use mydb
This will create a new database called mydb.
Step 2: Connect to the MongoDB Database in Node.js
Now that we have a MongoDB database set up, let's connect to it in Node.js. Create a new directory for your project and navigate into it:
mkdir myproject
cd myproject
Next, initialize a new Node.js project using the following command:
npm init
This will create a new package.json file in your project directory.
Now, let's install the mongodb package using npm:
npm install mongodb
This will install the mongodb package and add it to your package.json file as a dependency.
Next, create a new file called app.js in your project directory and add the following code to it:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/mydb';
MongoClient.connect(url, (err, client) => {
if (err) throw err;
const db = client.db('mydb');
// perform database operations here
client.close();
});
This code connects to the mydb database on your local MongoDB server. The MongoClient object is used to connect to the database and the db object is used to perform database operations.
Step 3: Create Documents in MongoDB
Now that we have connected to the MongoDB database in Node.js, let's create some documents. Add the following code to your app.js file:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/mydb';
MongoClient.connect(url, (err, client) => {
if (err) throw err;
const db = client.db('mydb');
const collection = db.collection('users');
const user = { name: 'John Doe', email: 'johndoe@example.com' };
collection.insertOne(user, (err, result) => {
if (err) throw err;
console.log(`Inserted ${result.insertedCount} document`);
client.close();
});
});
This code creates a new users collection in the mydb database and inserts a new user document with a name and email field.
Step 4: Retrieve Documents in MongoDB
Now that we have created some documents in MongoDB, let's retrieve them using Node.js. Add the following code to your app.js file:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/mydb';
MongoClient.connect(url, (err, client) => {
if (err) throw err;
const db = client.db('mydb');
const collection = db.collection('users');
collection.find({}).toArray((err, docs) => {
if (err) throw err;
console.log(`Found ${docs.length} documents`);
docs.forEach((doc) => {
console.log(doc);
});
client.close();
});
});
This code retrieves all documents in the users collection and logs them to the console.
Step 5: Update Documents in MongoDB
Now that we know how to create and retrieve documents in MongoDB, let's learn how to update them. Add the following code to your app.js file:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/mydb';
MongoClient.connect(url, (err, client) => {
if (err) throw err;
const db = client.db('mydb');
const collection = db.collection('users');
const filter = { email: 'johndoe@example.com' };
const update = { $set: { name: 'Jane Doe' } };
collection.updateOne(filter, update, (err, result) => {
if (err) throw err;
console.log(`Updated ${result.modifiedCount} document`);
client.close();
});
});
This code updates the name field of the document with the email johndoe@example.com to Jane Doe.
Step 6: Delete Documents in MongoDB
Finally, let's learn how to delete documents in MongoDB. Add the following code to your app.js file:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/mydb';
MongoClient.connect(url, (err, client) => {
if (err) throw err;
const db = client.db('mydb');
const collection = db.collection('users');
const filter = { email: 'johndoe@example.com' };
collection.deleteOne(filter, (err, result) => {
if (err) throw err;
console.log(`Deleted ${result.deletedCount} document`);
client.close();
});
});
This code deletes the document with the email johndoe@example.com from the users collection.
Conclusion
In this tutorial, we have covered the basic CRUD operations in MongoDB using Node.js. We have learned how to connect to a MongoDB database, create documents, retrieve documents, update documents, and delete documents. With this knowledge, you can start building powerful Node.js applications that leverage the flexibility and scalability of MongoDB.