1. Introduction
In this tutorial, our main objective is to understand how to perform Create, Read, Update, and Delete (CRUD) operations using Mongoose and Express.js. Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js that simplifies interactions with MongoDB, while Express.js is a minimal and flexible Node.js web application framework.
By the end of this tutorial, you will be able to build a simple application that can perform CRUD operations using Express.js and Mongoose.
Prerequisites: Basic understanding of JavaScript, Node.js, Express.js, and MongoDB.
2. Step-by-Step Guide
Firstly, we need to set up a new Express.js application. Install Express and Mongoose using npm (node package manager) with the following command:
npm install express mongoose
This will create a new Express.js application and install the necessary packages.
Now, we can start with our CRUD operations:
Create Operation
The 'create' operation can be performed in Mongoose using the 'save' method. This method is available on each instance of the model.
let User = new UserModel({
name: 'John Doe',
email: 'john@example.com'
});
User.save((err, user) => {
if (err) return console.error(err);
console.log("User saved successfully:", user);
});
Read Operation
We can retrieve documents from MongoDB using 'find', 'findOne', and 'findById' methods. 'find' returns all documents, 'findOne' returns a single document, and 'findById' finds a document by its unique _id.
// get all users
UserModel.find((err, users) => {
if (err) return console.error(err);
console.log(users);
});
// get a single user
UserModel.findOne({ name: 'John Doe' }, (err, user) => {
if (err) return console.error(err);
console.log(user);
});
Update Operation
Mongoose provides 'updateOne', 'updateMany', and 'findByIdAndUpdate' methods for updates. Here's an example of 'findByIdAndUpdate':
UserModel.findByIdAndUpdate(userId, { name: 'Jane Doe' }, { new: true }, (err, user) => {
if (err) return console.error(err);
console.log("User updated successfully:", user);
});
Delete Operation
We can delete documents using 'deleteOne', 'deleteMany', and 'findByIdAndRemove' methods.
UserModel.findByIdAndRemove(userId, (err) => {
if (err) return console.error(err);
console.log("User deleted successfully");
});
3. Code Examples
Refer to the above examples for understanding. Each example includes code snippets, detailed comments, and expected results.
4. Summary
5. Practice Exercises
Solutions:
let newUser = new UserModel({
name: 'Alice',
email: 'alice@example.com'
});
newUser.save((err, user) => {
if (err) return console.error(err);
console.log("User saved successfully:", user);
});
UserModel.find((err, users) => {
if (err) return console.error(err);
console.log(users);
});
UserModel.findOneAndUpdate({ name: 'Alice' }, { name: 'Bob' }, { new: true }, (err, user) => {
if (err) return console.error(err);
console.log("User updated successfully:", user);
});
UserModel.findOneAndRemove({ name: 'Bob' }, (err) => {
if (err) return console.error(err);
console.log("User deleted successfully");
});
These exercises will help you get more familiar with CRUD operations in Mongoose and Express.js.