Handling CRUD Operations with MongoDB

Tutorial 2 of 5

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.