Express.js / Express.js and MongoDB

Performing CRUD Operations with Mongoose

In this tutorial, we'll cover how to perform CRUD operations using Mongoose in an Express.js application. You'll learn how to create, read, update, and delete data from a MongoDB …

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Covers integrating Express.js with MongoDB for data storage and retrieval.

1. Introduction

1.1 Brief Explanation of the Tutorial's Goal

The aim of this tutorial is to guide you through the process of performing CRUD (Create, Read, Update, Delete) operations using Mongoose in an Express.js application. These are the most common operations that you'll need when interacting with a MongoDB database.

1.2 What the User Will Learn

By the end of this tutorial, you will be comfortable in performing CRUD operations, understanding Mongoose schemas, models and the usage of various Mongoose methods for data manipulation.

1.3 Prerequisites

  • Basic understanding of JavaScript
  • Node.js and MongoDB installed on your computer
  • Familiarity with Express.js

2. Step-by-Step Guide

2.1 Mongoose and Express Setup

Firstly, create a new directory for your project and initialize a new Node.js project by running npm init -y. Install Express.js and Mongoose by running npm install express mongoose.

Create your server file (app.js) and set up a basic server.

const express = require('express');
const app = express();
const port = 3000;

app.listen(port, () => console.log(`Server running on port ${port}`));

Next, connect to your MongoDB database using Mongoose.

const mongoose = require('mongoose');

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

2.2 Defining a Mongoose Schema and Model

Before performing CRUD operations, define a Mongoose schema and model. The schema defines the shape of the documents in MongoDB collection and the model provides an interface for CRUD operations.

const courseSchema = new mongoose.Schema({
  name: String,
  author: String,
  tags: [ String ],
  date: { type: Date, default: Date.now },
  isPublished: Boolean
});

const Course = mongoose.model('Course', courseSchema);

3. Code Examples

3.1 Create Document

Create a document in MongoDB by instantiating the model and calling the save() method.

async function createCourse() {
  const course = new Course({
    name: 'Node.js Course',
    author: 'John Doe',
    tags: ['node', 'backend'],
    isPublished: true
  });

  const result = await course.save();
  console.log(result);
}

createCourse();

3.2 Read Document

You can read documents using various Mongoose methods like find(), findById(). These methods return a Query which you can execute by calling exec() or using async/await.

async function getCourses() {
  const courses = await Course
    .find({ author: 'John Doe', isPublished: true })
    .limit(10)
    .sort({ name: 1 })
    .select({ name: 1, tags: 1 });
  console.log(courses);
}

getCourses();

3.3 Update Document

Update a document using updateOne(), findByIdAndUpdate() methods. These methods can directly update the document in the database, or you can first find the document, modify its properties and then save it.

async function updateCourse(id) {
  const course = await Course.findById(id);
  if (!course) return;

  course.isPublished = true;
  course.author = 'Another Author';

  const result = await course.save();
  console.log(result);
}

updateCourse('60c72b5f7284ad3d8c05b2e9');

3.4 Delete Document

Delete a document using deleteOne(), findByIdAndRemove() methods.

async function deleteCourse(id) {
  const result = await Course.deleteOne({ _id: id });
  console.log(result);
}

deleteCourse('60c72b5f7284ad3d8c05b2e9');

4. Summary

In this tutorial, we've covered how to perform CRUD operations using Mongoose in an Express.js application. We've seen how to define a Mongoose schema and model, and how to create, read, update, and delete documents in MongoDB.

5. Practice Exercises

  1. Create a new Mongoose schema and model for a 'User' with fields: name (string), email (string), password (string), and createdAt (date).
  2. Using this 'User' model, create a new user, read all users, update a user's email, and delete a user.
  3. Add password hashing before saving a user document.

Remember to test your work and understand each operation. Happy Coding!

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

Random Name Generator

Generate realistic names with customizable options.

Use tool

Case Converter

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

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

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