Express.js / REST APIs with Express.js

Handling CRUD Operations with MongoDB

In this tutorial, we will explore how to handle CRUD operations with MongoDB in a Node.js/Express.js application. You will learn how to create, read, update, and delete records in…

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores building RESTful APIs using Express.js and best practices for API design.

1. Introduction

This tutorial aims to provide a step-by-step guide to handling CRUD (Create, Read, Update, Delete) operations with MongoDB in a Node.js/Express.js application. By the end of this tutorial, you should be able to:

  • Understand the basics of MongoDB
  • Connect a Node.js/Express.js application to a MongoDB database
  • Perform CRUD operations in MongoDB

Prerequisites:

  • Basic understanding of JavaScript and Node.js
  • Installed Node.js, Express.js, and MongoDB in your local environment

2. Step-by-Step Guide

Before we start, we need to install a MongoDB driver to interact with the MongoDB database. We'll use Mongoose, an elegant MongoDB object modeling for Node.js.

npm install mongoose

Connect to MongoDB

First, we'll connect to MongoDB using Mongoose.

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/my_database', {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => console.log('Connected to MongoDB'))
.catch((err) => console.log('Failed to connect to MongoDB', err));

Define a Model

We will create a Book model for our CRUD operations.

const bookSchema = new mongoose.Schema({
    title: String,
    author: String,
    published_year: Number
});

const Book = mongoose.model('Book', bookSchema);

3. Code Examples

Create a Document

To create a new book, we'll use the save method.

let book = new Book({
    title: 'Moby Dick',
    author: 'Herman Melville',
    published_year: 1851
});

let result = await book.save();
console.log(result);

Read a Document

To fetch all books, we'll use the find method.

let books = await Book.find();
console.log(books);

Update a Document

To update a book, we'll use the updateOne method.

let result = await Book.updateOne({ _id: id }, {
    $set: {
        title: 'Updated Title'
    }
});

console.log(result);

Delete a Document

To delete a book, we'll use the deleteOne method.

let result = await Book.deleteOne({ _id: id });
console.log(result);

4. Summary

In this tutorial, we've learned how to perform CRUD operations in MongoDB using Mongoose. We connected a Node.js/Express.js application to a MongoDB database, defined a model, and performed create, read, update, and delete operations.

To further your knowledge, you might want to explore data validation with Mongoose and handling relational data in MongoDB.

5. Practice Exercises

  1. Create a User model with fields name (String), email (String), and password (String). Write a script to create a new user.

  2. Write a script to fetch all users from the database.

  3. Write a script to update the name of a user.

  4. Write a script to delete a user from the database.

Remember to test your scripts after writing them to ensure they are working as expected.

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

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

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