Free Ebook cover How to create APIs in NodeJS from basic to advanced

How to create APIs in NodeJS from basic to advanced

5

(1)

149 pages

Creating a CRUD with NodeJS and MongoDB: Creating controllers for each CRUD operation

Capítulo 91

Estimated reading time: 4 minutes

Audio Icon

Listen in audio

0:00 / 0:00

One of the most crucial parts of developing APIs in NodeJS is creating controllers for each CRUD operation (Create, Read, Update, Delete). These controllers are responsible for managing the business logic of each operation and interacting with the MongoDB database. In this chapter, we will detail the process of creating these controllers.

Create Controller

The Create controller is responsible for creating new records in the database. In NodeJS, this is done using the Mongoose template's 'save' function. The code for a Create controller might look something like:


  exports.create = function(req, res) {
    var newRecord = new Model(req.body);
    newRecord.save(function(err, record) {
      if (err) {
        res.send(err);
      }
      res.json(record);
    });
  };
  

This code creates a new record using the data received in the HTTP request and then saves the record to the database. If an error occurs during this process, it will be caught and sent as a response. Otherwise, the new record is sent as a response.

Read Controller

The Read controller is responsible for reading records from the database. This can be done using the 'find' function of the Mongoose template. The code for a Read controller might look something like:


  exports.read = function(req, res) {
    Model.find({}, function(err, records) {
      if (err) {
        res.send(err);
      }
      res.json(records);
    });
  };
  

This code reads all records from the database and sends them as a response. If an error occurs during this process, it will be caught and sent as a response.

Continue in our app.

You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.

Or continue reading below...
Download App

Download the app

Update Controller

The Update controller is responsible for updating existing records in the database. This can be done using the 'findByIdAndUpdate' function from the Mongoose template. The code for an Update controller might look something like:


  exports.update = function(req, res) {
    Model.findByIdAndUpdate(req.params.id, req.body, {new: true}, function(err, record) {
      if (err) {
        res.send(err);
      }
      res.json(record);
    });
  };
  

This code updates a specific record, identified by the ID passed as a parameter in the HTTP request. New data for the record is passed in the body of the request. If an error occurs during this process, it will be caught and sent as a response. Otherwise, the updated record is sent as a response.

Delete Controller

The Delete controller is responsible for deleting records from the database. This can be done using the 'findByIdAndRemove' function from the Mongoose template. The code for a Delete controller might look something like:


  exports.delete = function(req, res) {
    Model.findByIdAndRemove(req.params.id, function(err, record) {
      if (err) {
        res.send(err);
      }
      res.json({ message: 'Record successfully deleted' });
    });
  };
  

This code deletes a specific record, identified by the ID passed as a parameter in the HTTP request. If an error occurs during this process, it will be caught and sent as a response. Otherwise, a success message is sent in response.

In summary, creating controllers for each CRUD operation in NodeJS involves defining functions that handle HTTP requests and interact with the MongoDB database. Each controller is responsible for a specific CRUD operation and must deal with possible errors that may occur during the process.

Now answer the exercise about the content:

_What is the role of the 'Update' controller in CRUD with NodeJS and MongoDB?

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

You missed! Try again.

The Update controller is responsible for updating existing records in the database using functions like 'findByIdAndUpdate' in Mongoose. It changes the specified data of a record identified by an ID from an HTTP request and returns the updated record or error information.

Next chapter

Creating a CRUD with NodeJS and MongoDB: Implementing functions to create, read, update and delete data

Arrow Right Icon
Download the app to earn free Certification and listen to the courses in the background, even with the screen off.