Performing CRUD Operations with MongoDB and Mongoose
Explore how to perform full CRUD operations in Express.js applications using MongoDB and Mongoose. Understand how to create, read, update, and delete user data through API endpoints, along with proper error handling and method distinctions like PUT versus PATCH for updates.
We'll cover the following...
By now, we know how to connect to MongoDB and define data structure using Mongoose schemas and models. But a database isn’t much use if we can’t add, retrieve, update, or delete data—that’s where CRUD operations come in.
Using Mongoose, we can implement CRUD (create, read, update, delete) operations by building API endpoints for:
Creating new records (
POST)Retrieving records (
GET)Updating records (
PUT&PATCH)Deleting records (
DELETE)
These operations are the foundation of any API that interacts with a database.
In a previous lesson, we defined the User schema and model using Mongoose. In this lesson, we’ll use that model to implement full CRUD operations.
Creating a new record (POST request)
To add a new user to the database, we use the POST method. Clients send user data as a JSON document, which our API processes and stores. The request body must be a JSON document that follows the Mongoose schema to ensure proper field alignment.
Explanation:
Line 1: Define a
POSTroute at/usersto handle new user creation. It use anasyncfunction to handle the database query asynchronously.Line 3: Create a new User instance using
req.body, which contains the client-supplied data in JSON format.Line 4: Call
.save()on the user instance to store the new document in the database.Line 5: ...