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…

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explains 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

  1. Create a new user with the name 'Alice' and email 'alice@example.com'.
  2. Retrieve all users from the database and log them.
  3. Update the name of 'Alice' to 'Bob'.
  4. Delete the user 'Bob'.

Solutions:

  1. 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);
});
  1. Retrieving all users
UserModel.find((err, users) => {
  if (err) return console.error(err);
  console.log(users);
});
  1. 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);
});
  1. 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.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Random Password Generator

Create secure, complex passwords with custom length and character options.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

PDF Splitter & Merger

Split, merge, or rearrange PDF files.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI 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 article

AI 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 article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help