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…
Section overview
5 resourcesExplores 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
-
Create a
Usermodel with fieldsname(String),email(String), andpassword(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.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article