How to effectively manage Mongoose Query Exceptions in Express.js

Let's imagine a scenario where I need to execute a Mongoose query in an Express post route:

app.post("/login",(req,res)=>{
    const username = req.body.username
    const password = req.body.password
    User.find({username:username},(err,user)=>{
        if (err) handleError(err)
        //if user exists
        if (user.length) {
            //check password
            if (user.password === password) {
                //assign jwt, redirect
            } else {
                //"username/password is incorrect"
            }
        } else {
            //"username/password is incorrect"
        }
    })
})

I'm uncertain about the purpose of the handleError function. Since it involves a simple query in Mongoose, what kinds of errors could potentially occur and how should they be handled within the handleError function? Additionally, what type of response should I provide to the user in such cases?

Answer №1

In my view, here is what you should do:

  • Consider implementing promises with async/await.
  • Avoid catching errors in your middleware and instead manage errors in the top-level express error handler. Further details can be found here.
  • In the top-level express error handler, choose the appropriate action based on the environment. For instance, for production, return a simple message like:
    return res.status(500).json({ message: "Our server is currently inaccessible, please try again later." });
    . In a local environment, send a JSON payload containing the error using:
    return res.status(500).json({ err: <Error> });
    .

To summarize, ensure your code resembles this structure:

app.post('/login', async (req, res) {
  
  // Utilize ES6 Destructuring
  const { username, password } = req.body;

  // Opt for findOne over find for faster query execution
  const user = await User.findOne({ username });

  if (!user || (user.password !== hashFunction(password))) {
    return res.status(403).json({ message: 'Invalid credentials' });
  }

  // Generate JWT token and redirect
});

Answer №2

To handle Mongoose response, it is recommended to send an error message in your response.

app.post("/login",(req,res)=>{
    const userName = req.body.userName
    const password = req.body.password
    User.findOne({userName:userName},(error,user)=>{
        if (error){
          return res.status(400).json({message:"Error finding user.", error: error });
        }
        //if user exists
        if (user) {
            //check password
            if (user.password === password) {
                //generate jwt token, redirect
            } else {
                //respond with "Invalid username or password"
            }
        } else {
            //respond with "Invalid username or password"
        }
    })
})

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

Express JS redirect does not update the URL and fails to load static files

I'm currently developing an application using Express.js to build the REST interface on Node.js. Additionally, I am using jQuery Mobile for the client-side pages. One issue I am facing is with redirects when users try to access a restricted or inacce ...

Jquery UI slider malfunctioning would require troubleshooting

I am currently working on implementing slider functionality with jQuery. The slider is visible and functioning properly in terms of taking in values, however, the values are not displayed on the screen as expected. I have used console.log to track the ui.v ...

Filtering documents in MongoDB based on a sub-document using Java 8 Stream Filter

Struggling to successfully filter a sub-document. Example Record: [Document{{_id=597608aba213742554f537a6, upp_id=, content_id=597608aba213742554f537a3, idmapping=Document{{ptype=PDF, clientid=12345, normalizedclientid=12345, systeminstanceid=, sourcesch ...

The parent's height dynamically adjusts based on the height of its visible children using only CSS

I am dealing with the following structure: <div class="body"> <div class="wrapper"> <div class="dialog"> <div class="content-0"></div> <div class="content-1&quo ...

Having trouble retrieving input field values with Angular.js

I am struggling to access the input field values in my Angular.js application. Below is the code snippet I am using: <div class="input-group bmargindiv1 col-md-12"> <span class="input-group-addon ndrftextwidth text-right" style="width:180px"& ...

The Shopify CLI's node serving function has not been operational for a project that is one year old

As I embark on refactoring my previous Shopify project, I encounter an issue when executing the command "shopify node serve" which prompts the following error message. "This command can only be run within node projects." Despite this error message, my pr ...

Comparison of Transferred and Size columns within the Network tab of Mozilla Firefox

Can someone clarify the distinction between the Transferred column and Size column for me? I'm wondering if it's related to the disparity between compressed and uncompressed files. I haven't compressed my files on my Node.js Express server, ...

Open the HTML document and access the file contents

I'm having trouble reading a text file from my computer onto a website. It works fine in Internet Explorer, but won't work in Chrome. I don't have much experience with HTML, so any help would be much appreciated! <html> <body> ...

Exploring Web Application Testing using Vows and Tobi

Just diving into the world of node.js testing and could use some guidance. I'm looking to run some basic tests on my express webapp using vows and tobi, such as checking if the login route functions properly. var vows = require('vows'); v ...

Using promises and the fetch function to connect to a database

I am attempting to utilize promises with the fetch() function in order to access MongoDB from the front-end, but I am encountering some issues. var Promise = () => ( new Promise((resolve, reject) => { //perform certain actions, make requests ...

React failing to display basic component

As a newcomer to React, I have a question regarding rendering a basic React component. Here is my setup in index.html: <!DOCTYPE html> <html lang="en> <head> <title>React</title> </head> <body> < ...

Issues with click events in the navigation menu

How can I make my menu close when clicking on other parts of my website, instead of opening? I know that I should use a click event for this, but when I implemented a click event, my menu encountered 2 unwanted problems: 1- Whenever I clicked on a menu i ...

Exploring the world of chained JavaScript Promises for automatic pagination of an API

Dealing with a paged API that requires fetching each page of results automatically has led me to construct a recursive promise chain. Surprisingly, this approach actually gives me the desired output. As I've tried to wrap my head around it, I've ...

How come I'm not receiving an error message when I enter an incorrect email or password?

Whenever I try to log in with the wrong password and email, no error message is displayed. Instead, it simply logs me in and takes me to the main page. Can someone please assist me in implementing an error message display for incorrect login details? imp ...

Utilize Node.js to proxy Angular requests to a service hosted on Azurewebsites

I am trying to set up a proxy post request in my Node.js server and receive a response from the target of this request. Below is an excerpt from my server.js file code where I have implemented the proxy, but I am facing a issue with not receiving any respo ...

Designing a sequential bar graph to visualize intricate data using AmCharts

I received the following response from the server in JSON format: [{ "data1": { "name": "Test1", "count": 0, "amount": 0, "amtData": [ 0,0,0,0 ], "cntData": [ 0,0,0,0 ], "color": "#FF0F00" }, "data2": { ...

Retrieving information from MongoDB to populate the Redux store

Currently, I have successfully set up my Node API and MongoDB. My next focus is on integrating Redux into my application. Below are some code snippets that I would like to share: The Server Order controller is functioning as expected : const getTotal = as ...

Leveraging Discord.js to retrieve all messages sent while the bot was inactive

My plan is to create a bot that will store all messages sent in a channel into a txt file on my computer. However, the challenge is that since my computer is not always on when the bot is running, there are gaps in the stored messages in the .txt file. I a ...

Setting the selected value of a static select menu in Angular 2 form

I'm having an issue with my Angular 2 form that includes a static select menu. <select formControlName="type" name="type"> <option value="reference">Referentie</option> <option value="name">Aanhef</option> &l ...

What possible reasons could there be for my vue project failing to load the JavaScript file?

I encountered an issue with my login page and script.js file while setting up my project. Strangely, my Vue application is not loading the JavaScript file as expected. The console displays this error message: The error seems to be related to a template in ...