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:
Prerequisites:
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
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));
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);
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);
To fetch all books, we'll use the find
method.
let books = await Book.find();
console.log(books);
To update a book, we'll use the updateOne
method.
let result = await Book.updateOne({ _id: id }, {
$set: {
title: 'Updated Title'
}
});
console.log(result);
To delete a book, we'll use the deleteOne
method.
let result = await Book.deleteOne({ _id: id });
console.log(result);
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.
Create a User
model with fields name
(String), email
(String), and password
(String). Write a script to create a new user.
Write a script to fetch all users from the database.
Write a script to update the name of a user.
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.