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

Página 91

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

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.

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.

Next page of the Free Ebook:

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

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