16.10. Creating a CRUD with NodeJS and MongoDB: Error Handling

Página 94

One of the fundamental concepts in the development of web applications is CRUD (Create, Read, Update, Delete). These are the four basic types of functionality that most web systems need to perform at some point. In this chapter, we'll learn how to implement CRUD operations using NodeJS and MongoDB, with a special focus on error handling.

Creating a CRUD with NodeJS and MongoDB

To get started, we need a running MongoDB instance and a configured NodeJS application. Let's assume we already have a collection of users in our MongoDB database. Our goal is to create routes to add a new user, read existing users, update a user and delete a user.

Creating a new user (Create)

To create a new user, we need a POST route. In NodeJS, this can be done using the express package. First, we import express and initialize it. Next, we define a POST route that accepts the user's data as JSON in the request body. We use MongoDB's insertOne method to add the new user to our collection.


const express = require('express');
const app = express();
app.use(express.json());

app.post('/users', (req, res) => {
  const newUser = req.body;
  db.collection('users').insertOne(newUser, (err, result) => {
    if (err) {
      res.status(500).send({ error: 'An error occurred while creating the user' });
    } else {
      res.status(201).send(result.ops[0]);
    }
  });
});

Reading existing users (Read)

To read existing users, we need a GET route. We define this route and use MongoDB's find method to get all the users in our collection. The toArray method converts the result to an array for easy handling.


app.get('/users', (req, res) => {
  db.collection('users').find({}).toArray((err, users) => {
    if (err) {
      res.status(500).send({ error: 'An error occurred while fetching users' });
    } else {
      res.send(users);
    }
  });
});

Updating a user (Update)

To update a user, we need a PUT route. This route must include the user ID we want to update. We use MongoDB's findOneAndUpdate method to update the user. We specify the user ID as our search criteria and pass in the new user data.


app.put('/users/:id', (req, res) => {
  const userId = req.params.id;
  const newUserData = req.body;
  db.collection('users').findOneAndUpdate({ _id: ObjectId(userId) }, { $set: newUserData }, (err, result) => {
    if (err) {
      res.status(500).send({ error: 'An error occurred while updating the user' });
    } else {
      res.send(result.value);
    }
  });
});

Deleting a user (Delete)

To delete a user, we need a DELETE route. This route must also include the user ID we want to delete. We use MongoDB's findOneAndDelete method to delete the user.


app.delete('/users/:id', (req, res) => {
  const userId = req.params.id;
  db.collection('users').findOneAndDelete({ _id: ObjectId(userId) }, (err, result) => {
    if (err) {
      res.status(500).send({ error: 'An error occurred while deleting the user' });
    } else {
      res.send(result.value);
    }
  });
});

Error handling

Error handling is a crucial part of any application development. On all our routes, we check whether an error occurred during database operation. If an error occurred, we respond with an HTTP status 500 and an error message. This lets the customer know that something has gone wrong.

In a production environment, you should also consider logging errors. This can be done using a package like winston or morgan. These packages allow you to automatically log bug reports and other useful information.

In short, CRUD is a fundamental concept in web application development. With NodeJS and MongoDB, we can implement CRUD operations efficiently and easily. Error handling is a crucial part of this as it allows us to handle unexpected situations in an elegant way.

Now answer the exercise about the content:

What does the acronym CRUD mean in the context of web application development and what operations does it represent?

You are right! Congratulations, now go to the next page

You missed! Try again.

Next page of the Free Ebook:

9516.11. Creating a CRUD with NodeJS and MongoDB: Unit Tests

Earn your Certificate for this Course for Free! by downloading the Cursa app and reading the ebook there. Available on Google Play or App Store!

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text