Performing CRUD Operations with Mongoose

Tutorial 2 of 5

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!