Avoid receiving a 404 error when using an invalid ID

When trying to set up my workoutId param, I encounter the following error:

UnhandledPromiseRejectionWarning: CastError: Casting to ObjectId failed for value "5fb02bd8b61abc02" at path "_id" for model "Workout"

If the workoutId exists, I can successfully make a GET request. However, when attempting with an id that doesn't exist, it should result in a 404 response but it does not. Am I overlooking something?

workoutsRouter.param('workoutId', async (req, res, next, workoutId) => {
  try {
    await mongoose.connect('mongodb+srv://nalanart:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="640c0d000d0a0314051717130b16002407081117100116544a560d14080c4a090b0a030b00064a0a0110">[email protected]</a>/workout-app-db?retryWrites=true&w=majority', 
    { useNewUrlParser: true, useUnifiedTopology: true })

    const workout = await Workout.findById(workoutId).exec()

    if(Object.keys(workout).length === 0) {
      res.sendStatus(404)
    } else {
      req.workout = workout
      next()
    }

  } catch(error) {
    throw error
  }
  
})

Answer №1

To address your query, all you need to do is include res.sendStatus(404) in the catch block.

It's crucial to understand the meaning behind different status codes.

404 signifies that the requested value was not found. Therefore, if the query executes successfully but does not return any documents, sending a 404 response is appropriate. However, if there is a failure in the query execution, it is advisable to use a different status code.

In such scenarios, using 400 as the status code may be more suitable. As per industry standards and resources like Mozilla:

400 Bad Request: The server cannot process the request due to invalid syntax.

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

Retrieving JavaScript return values in a C# WebBrowser control within a WPF application

I utilized JavaScript injection into WebBrowser control in C# (System.Windows.Controls.WebBrowser) to achieve, <C#> IHTMLDocument2 webdoc = (IHTMLDocument2)webBrowser1.Document; string var = File.ReadAllText("C:/.../Resources/script.txt"); object re ...

Is there a way to modify the state following a sorting operation?

How can I properly update the state after sorting by salary? state = { workers: [ {name: 'Bob', surname: 'Meljanski', salary: 5140}, {name: 'Michel', surname: 'Hensson', salary: 5420}, {n ...

I'm seeking guidance on how to delete a specific ul li element by its id after making an ajax request to delete a corresponding row in MySQL database. I'm unsure about the correct placement for the jQuery

I have created an app that displays a list of income items. Each item is contained within an li element with a unique id, along with the item description and a small trash icon. Currently, I have implemented code that triggers an AJAX call when the user cl ...

After an asynchronous query using Mongoose in an Express route, I am unable to make any changes to the variable. It remains unchanged

I am facing an issue with modifying an empty array let last_activity = [] based on the result of a Mongoose query within an Express route. For troubleshooting purposes, I am currently trying to change it to [1, 2, 3]. Despite attempting different approache ...

The ng-click event for the reset button is limited to a single use

There seems to be a problem with the reset button functionality on my webpage. Although it initially works, it only works once and then requires a reload of the page to function again. Here is the JS code: var ctrl = this; var original_device = angular.c ...

Tips for troubleshooting and resolving issues with Mongoose and MongoDB in a MEAN stack

Currently learning the MEAN stack and utilizing npm start to run my application. Facing some challenges with Mongoose and MongoDB, but only receiving POST /page 500 63.925 ms - 961 Here is the directory setup of my app, following guidance from this tutori ...

Various web browsers are displaying distinct jQuery errors when executing the code

I'm currently working on validating and uploading images using multiple accept inputs with the help of jQuery, AJAX, and PHP. I have successfully added a validation function that is working correctly, but the form is not submitting. Additionally, Chro ...

Why do `setTimeout` calls within JavaScript `for` loops often result in failure?

Can you help me understand a concept? I'm not inquiring about fixing the code below. I already know that using the let keyword or an iffe can capture the value of i. What I need clarification on is how the value of i is accessed in this code snippet. ...

Utilize MySQL/Javascript to determine percentages

I'm facing a challenge with an SQL query in Entrinsik's Informer. I need to calculate a percentage using JavaScript on the result, but unfortunately, Informer cannot access data down columns (such as the total for the percentage). Therefore, I ha ...

Initiate the printing process by executing the window.print() function. As the document is being

Here's the code snippet : <body> <div class="headerCont noprint"> <div class="headerHold"> <div class="logoCont"><img src="images/logo.jpg" width="104" height="74" alt="Logo"> ...

What are some ways to incorporate JQuery with getElementById?

i am trying to retrieve all input elements within a form using JavaScript formEditable = document.getElementById("formid").getElementsByTagName("input"); However, I would like to achieve the same result using jQuery instead formEditable = $("#formid").f ...

Implementing a Context Menu with a Single Click

I need assistance with creating a context menu that appears when the user clicks inside an HTML5 canvas. I want to have functions called when an item in the menu is selected. Can anyone provide guidance on how to achieve this? ...

What sets local Node package installation apart from global installation?

My curiosity sparked when I began the process of installing nodemon through npm. Initially, I followed the recommended command and noticed the instant results displayed on the right side of my screen: npm i nodemon This differed from the installation ins ...

Achieving CSS transition effects using the .appendChild function in JavaScript

When using the mouseenter event, I have a JavaScript function applied to an svg path element: const fadeIn = (event, locale) => { event.target.style.fill = 'hwb(' + (120 - score[locale] * 1.2) + ' 0% 0% / 1)' } This function wor ...

true not redirecting to 404 page when axios request fails

I have implemented Axios to access a basic API. My goal is to direct the user to the default Next.js 404 page in case of a failed request with a 404 error code. I have set the notFound boolean to true if the request status is 404. There are a total of 10 u ...

Tips on using ajax in node.js for achieving partial postback

Currently, I am utilizing the node.js (express framework and hbs engine) along with mongodb for the development of an application. My goal is to incorporate an ajax call that allows for partial post back on the page. ...

Divide the information in the table across several pages for easier printing

I have encountered an architectural challenge with my server-side React app. The app renders charts and tables with page breaks in between to allow a puppeteer instance to print the report for users in another application. The issue I'm facing is mak ...

`Is there a way to retrieve the ID of an element upon clicking on it?`

Can you help me with a JavaScript query? I have two HTML div elements with ids of 'div1' and 'div2'. When I click on any of the divs, I want to display the id of the clicked div. Any thoughts? <div id="div1"></div> <div ...

Dealing with Angular CORS Problems While Sending Successive Requests

I am currently working with Angular 6 and my backend consists of a node API. Occasionally, I encounter a CORS issue while making HTTP GET requests every 5 seconds. const url = 'https://<removed>.com/api/v1/transactions/' + transactionI ...

What is the best way to incorporate a listener into an Angular directive?

I have a custom directive that generates a dynamic Google chart. My goal is to activate an event handler on the controller's scope whenever the directive detects an event from the chart. For example: http://plnkr.co/edit/yn4KuQfrYvlQNbPSWk3Q?p=previe ...