The application experiences a sudden failure when Mongoose is unable to locate the specified item

I am facing an issue where my app crashes when mongoose is unable to find the item. I want to display a 404 error page instead.

Here is the code snippet:

  try {
    let theBeverage = Product.findOne({ _id: beverageId });
    await theBeverage.then((data) => (theBeverage = data));
    res.render("menuetail.ejs", { theBeverage });
  } catch (error) {
    res.render("404.ejs").status(404);
  }

I anticipate that it will show a 404 page in such cases.

Answer №1

It is recommended to avoid using then when working with async await.

Consider the following approach:

try {
  const selectedProduct = await Product.findOne({ _id: productId });      
  res.render("productDetails.ejs", { selectedProduct });
} catch (error) {
  res.render("404.ejs").status(404);
}  

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

What is the best method for navigating and passing data in dynamic routing with NEXT.JS?

In the process of developing my next.js ecommerce app, I am utilizing Firebase to fetch product data. My goal is to have users click on a product and be redirected to a new page displaying the details of that particular product. However, despite using the ...

Parameters in Typescript decorators

Can someone help me understand the various parameters of a Typescript decorator? function myDecorator(target) { // do something with 'target' ... } In the given example, I am aware that 'target' represents the function/class to wh ...

Update information interactively in Vuejs for all stored data

I am facing an issue with my code where the totalUserPosts value is returning as Zero after an AJAX call, and I need to find a solution for this problem. new Vue({ el: "#app", data: { totalUserPosts:0, }, methods:{ getPostsAjax () { $.ajax({ ...

Embrace AngularJS: Employ the ".then" method and retrieve the response

In order to send a http request and receive the response of this request, I am trying to implement a mechanism where if the data is successfully saved, I can retrieve database information, and if it fails to save, I can track errors. To achieve this, I pla ...

JWT refresh and access tokens: A dynamic duo for secure authentication

In my project, I utilize jwt tokens with a strategic approach. Long-lived refresh tokens are employed for authentication purposes, while short-lived access tokens are used to safeguard protected resources. To enhance security against xss attacks, the refre ...

Encountered an issue with MongoDB connection - Authentication has failed

Encountering difficulties connecting to MongoDB while initiating a new MERN stack project: The code in server.js is as follows: const express = require('express'); const cors = require('cors'); const mongoose = require('mongoose&a ...

The error "ReferenceError: process is not defined in vue 3" is being

<script setup> import puppeteer from 'puppeteer'; const onChange = async () => { // Initializing the puppeteer library const browser = await puppeteer.launch(); // Creating a new page const page = await browser.newPage(); / ...

utilizing the value within the useState function, however, when attempting to utilize it within this.state, the tab switching feature fails

I am struggling to implement tab functionality in a class component. Even though I'm using this.state instead of useState, the tab switching is not working correctly. I have read the following articles but still can't figure it out: http ...

Retrieve data points from ol.layer.Vector using OpenLayers 4

Having recently started using OpenLayers, I find myself in a state of confusion. I'm attempting to retrieve all features from a kml vector layer, but have been unsuccessful thus far. It perplexes me as to what mistake I might be making. Below is the ...

Storing a collection of items in an array using jQuery

Looking to organize list items from multiple lists of the same class into an array. For example: <ul class="myList"> <li>item 1</li> <li>item 2</li> </ul> <ul class="myList"> <li>i ...

Using React Native to implement a slide bar that displays an image

Currently working on an app and aiming to implement a slider feature for emoji selection. Despite searching for suitable packages, I have not been able to find one that fits my requirements. As a result, I decided to use the react native slider instead. Ho ...

Verify whether the content within the Div has been modified

I am currently making changes to content within a <div> element. I would like to determine if the data in the <div> has been modified and, if so, save it in a session to persist on refresh. How can I verify if the data has been edited and then ...

The function is returning an undefined value in node.js due to the boolean condition

I have two functions. The first one is in auth.js, and it looks like this: const adminCheck = (req, res) => { console.log(“one”) UtilRole.roleCheck(req, res, ‘ADMIN’, (response) => { if(response) { return true ...

"Troubleshoot: jQuery UI accordion not functioning properly in response to

I've encountered an issue with the accordion functionality while working with dynamic data. To address this, I'm incorporating JavaScript to generate <div> and <h3> tags for the accordion. Here is the code snippet I am using: $(&ap ...

Dropdown menu featuring a customizable input field

Is it possible to have a drop-down list with an input textbox field for creating new items in the same dropdown menu? ...

Extending Mongoose's capabilities with header files for the "plugin" feature, utilizing the .methods and .statics methods

My task is to develop Typescript header files for a script that enhances my Mongoose model using the .plugin method. The current signature in the Mongoose header files looks like this: export class Schema { // ... plugin(plugin: (schema: Schema, opt ...

Exploring the CSS scale transformation alongside the Javascript offsetHeight attribute

After combining offsetHeight with scale transformation, I experienced a strange result. Below is my simple HTML code: <body> <div id="id01"> Some Text </div> <div id="id02" style="transform-origin: left top; transf ...

What are some effective ways of using the parent, before, and children selectors?

<table> <tr><td><input type="text" value="123"></td><td><input class="here" type="text"></td></tr> <tr><td><input type="text" value="333"></td><td><input class=" ...

Remove an item from the DOM instantly with React

Having trouble synchronously removing a child from the container? Here is a simplified code snippet demonstrating the current solution using the useState hook. type ChildProps = { index: number; id: string; remove: (index: number) => void; }; fun ...

The search box output will be the same as the JSON result

I have a server in Node.js that is able to read and process a JSON file containing various data, including unique user IDs. I have incorporated a search box into my HTML page, and I am seeking assistance with creating a jQuery method (which will require AJ ...