Search code examples
node.jsdatabasemongodbexpresswebapi

Redirect to an error page if query is not matched in Node+Express+MongoDB


I am developing a website form that will access information stored in a MongoDB database (imagine accessing a library catalog). To do so, I am using NodeJS, Express, MongoDB and views with EJS.

The code is working fine, but I would like to display an error page or something like that if no results are found. I have been trying for a while, but my code doesn't seem to work.

This is what I did so far. The full code is quite long, so I will paste only the relevant part in my index.js file:

//The querying code works, and the following two lines print the results in a view called "queryResult".
//filteredData is a filter I used to arrange the information in order.

    const libraryItems = await collection.aggregate(filteredData).toArray() 
       res.render("queryResult", {libraryItems : libraryItems})
    if(libraryItems == null){
      res.render("noResults") //I created a view called noResults.ejs in the folder "views"
      return
      }
    })

With this code, when a query is not successful, I get the view "queryResult" with an empty list of items. What I expect is to get the view "noResults" with a message informing the user that no results were found.

I think the solution must be quite simple, but I am not very experienced in coding, so I am not sure about how to solve it. Any help will be greatly apreciated.


Solution

  • You need to check the count of the items returned. And as I see, you are sending the render with result before checking it.

    const libraryItems = await collection.aggregate(filteredData).toArray()
    const libraryItems_count = libraryItems.length;
    
    if(!libraryItems || libraryItems == null || libraryItems_count < 1){
      res.render("noResults")
      return;
    }
    
    res.render("queryResult", {libraryItems : libraryItems});