...

/

Performing CRUD Operations with MongoDB and Mongoose

Performing CRUD Operations with MongoDB and Mongoose

Learn how to interact with a database in an Express.js API by implementing full CRUD operations using Mongoose.

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.

Press + to interact
app.post('/users', async (req, res, next) => {
try {
const user = new User(req.body);
await user.save();
res.status(201).send(user);
} catch (error) {
next(error);
}
});

Explanation:

  • Line 1: Define a POST route at /users to handle new user creation. It use an async function 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: If successful, return the created user along with a 201 Created response.

  • Lines 6–8: ...

Access this course and 1400+ top-rated courses and projects.