The REST API for HTTP DELETE does not validate for null values

Currently facing an issue while developing a RESTful API for a web service. I am attempting to delete an email, but first I need to confirm if the email actually exists. The problem arises when it fails to check if the email is null and does not return a 404 status code as expected. I am utilizing express and mongoose in this project.

router.delete('/:id', (req, res) => {
    const { id } = req.params;
    Mail.findById(id)
      .exec()
      .then((mail) => {
        if (!mail) {
          console.log(mail) // returns null
          return res.status(404);
        }
      })
      .then(
        Mail.deleteOne({ _id: id })
          .exec()
          .then(() => {
            res.status(200).json({
              message: 'Mail deleted',
            });
          })
          .catch((err) => {
            res.status(500).json({ error: err });
          })
      );
  });

Answer №1

To properly implement the code for deletion, you need to include the deletion logic within the first 'then' block as an else statement. This ensures that the necessary response is returned for the next 'then' block to utilize.

You can try the following approach:

Mail.findById(id)
      .exec()
      .then((mail) => {
        if (!mail) {
          console.log(mail); // returns null
          return res.status(404).send(); // a response should be sent
        }
        
        Mail.deleteOne({ _id: id })
          .exec()
          .then(() => {
            res.status(200).json({
              message: 'Mail deleted',
            });
          });
      }).catch((err) => {
            res.status(500).json({ error: err });
      })

PRO TIP: Consider familiarizing yourself with async await for cleaner code implementation!

If you opt for async/await, the code would appear as follows:

router.delete('/:id', async (req, res) => {
    const { id } = req.params;

    try {
      const mail = await Mail.findById(id);
      if(!mail) {
         return res.status(404).send();
      }

      await Mail.deleteOne({_id: id});      
      res.status(200).json({
              message: 'Mail deleted',
            });
    } catch(e) {
      res.status(500).json({ error: err });
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with visibility of pagination in AngularJS ui

I am facing an issue with pagination in my AngularJS UI application. I have a dataset that requires server-driven pagination due to its size. The problem I'm encountering is that the pagination element is not displaying on the page, even though I hav ...

Tips for managing this JavaScript JSON array

Here is an example of a JSON array: var data = { name: 'Mike', level: 1, children: [ { name: 'Susan', level: 2, }, { name: 'Jake', level: 2 }, { name: 'Roy', level: 2 }, ...

Utilizing DOMStringMap data to populate CSS URLs

I am attempting to create a universal CSS modification for a webpage element that resembles: <button data-action="link" class="cardImageContainer coveredImage cardContent itemAction lazy lazy-image-fadein-fast" data-blurhash="lo ...

Unearthing the worth of the closest button that was clicked

I am currently working on a profile management feature where I need to add students to the teacher's database. To achieve this, I am using jQuery and AJAX. However, I am encountering an issue where clicking the "add" button for each student listed on ...

Errors during the compilation of Webgl shaders in the Google Chrome browser

Currently, I am in the process of learning three.js by following this tutorial: . Despite the tutorial working well, I have encountered errors in my own code which seem like this: ERROR: 0:26: 'nuniform' : syntax error Three.js:325 precision hi ...

In Node.js, the context of the Express route handler is universally accessible

Is the route handler context global? This seems to make it difficult to pass an instance method of a class, or am I mistaken? For instance: App.all('/anyRoute', instanciatedClass.REST); Where .REST is a method on that specific instance. When t ...

Transform JSON information into an array

element below, I am facing a challenge. I need to convert the JSON format provided into an array format as shown in the second code block: [ { "Latitude": "-7.00786", "Longitude": "34.99805", "UserID": 0, "HTMLCode": "& ...

Highlight the navigation transition in the menu

Is there a more updated tutorial available for creating an underline effect that slides from one link to another when hovered over and remains at the clicked link? I have come across a tutorial on Underline transition in menu which seems to be based on th ...

Is there a way to focus on a specific iteration of the ngFor loop in Angular 9 using jQuery?

I'm working on a list of items inside a modal that uses *ngFor with checkboxes. The goal is to cross out the contents of an item when its checkbox is clicked. Here's the initial code using jQuery in home.component.ts: $('body').on(&apo ...

Using node.js with sqlite3 results in a callback to the route that returns an empty array

I have a sqlite3 database with some initial data. The function below works when run from the terminal: const db = require('./conn'); function select_user (callback) { let q = `select uid, uname, pwd from usr`; db.all(q, function (err, ...

Attempting to establish a connection with a MySQL database through the utilization of Node.js in combination with the mysql javascript client

Recently, I've been facing a challenge connecting to a MySQL database from my electron app: <script> var mysql = require('mysql'); var connection = mysql.createConnection({ host : '*********', ...

What steps can be taken to seek assistance for a specific function within a module while using the REPL in node.js?

Seeking Documentation in the form of Man pages for a function within a module in node.js using REPL. When using Console.dir(modObj), all the methods and properties associated with a module are listed. However, I am unable to locate any manual or help docu ...

While the find operation in mongoose failed to return any documents, the compass tool was successful in retrieving them

Objective To retrieve products based on category id from the 'products' collection in MongoDB using mongoose.find method. Expected Outcome vs. Actual Outcome The expected result is to receive all documents matching the specified category withi ...

Selenium in C#: Timeout issue with SendKeys and Error thrown by JS Executor

Attempting to insert the large amount of data into the "Textarea1" control, I have tried two different methods. The first method successfully inserts the data but occasionally throws a timeout error, while the second method results in a JavaScript error. A ...

The Vue DevTools are functioning as expected, but there seems to be an issue

Encountering a peculiar issue where the value displayed in Vue DevTools is accurate, matching what is expected in my data. When I first click on the "Edit" button for an item, the correct value appears in the browser window as intended. However, upon clic ...

Using Promise to manipulate objects and arrays returned from functions

https://i.stack.imgur.com/jvFzC.png router.get('/', function (req, res, next) { var size = req.params.size ? parseInt(req.params.size) : 20; var page = req.params.page ? req.params.page>0 ? (size&(parseInt(req.params.page)-1)) : ...

Encountering an error while attempting to launch an AngularJS application on Node.js? Let's

Currently, I am in the process of learning Angular. Whenever I attempt to run my code, an error message pops up: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7a737a7c6b6d70715f2b312f3115">[email protected]< ...

Learn how to create a logarithmic scale graph using CanvasJS by fetching data from an AJAX call

window.onload = function() { var dataPoints = []; // fetching the json data from api via AJAX call. var X = []; var Y = []; var data = []; function loadJSON(callback) { var xobj = new XMLHttpRequest(); xobj.overrideMimeType("applicatio ...

What is the best way to display the outcome in a popup window?

I am looking to display the result in a pop-up window. Code: <?php $con=mysqli_connect("localhost","root","1234","fyp"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $result = ...

What sets apart a class from a service in NativeScript?

I am embarking on the journey of learning Nativescript + Angular2, and while reading through the tutorial, I came across this interesting snippet: We’ll build this functionality as an Angular service, which is Angular’s mechanism for reusable classes ...