MongoDB / MongoDB with Node.js and Express
Performing CRUD with Mongoose and Express
In this tutorial, you will learn how to perform Create, Read, Update, and Delete (CRUD) operations using Mongoose and Express.js. Mongoose is a MongoDB object modeling tool that s…
Section overview
5 resourcesExplains integrating MongoDB with Node.js and Express for web applications.
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
- We have covered how to perform CRUD operations in Mongoose and Express.js.
- Next steps: Look into validation, complex queries, and relationships between documents.
- Additional resources: Mongoose Docs, Express.js Docs
5. Practice Exercises
- Create a new user with the name 'Alice' and email 'alice@example.com'.
- Retrieve all users from the database and log them.
- Update the name of 'Alice' to 'Bob'.
- Delete the user 'Bob'.
Solutions:
- Creating a new user
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);
});
- Retrieving all users
UserModel.find((err, users) => {
if (err) return console.error(err);
console.log(users);
});
- Updating a user
UserModel.findOneAndUpdate({ name: 'Alice' }, { name: 'Bob' }, { new: true }, (err, user) => {
if (err) return console.error(err);
console.log("User updated successfully:", user);
});
- Deleting a 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.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Random Password Generator
Create secure, complex passwords with custom length and character options.
Use toolLatest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article