Node Express application experiences issues with Handlebars rendering additional empty objects from JSON arrays

Currently, I am attempting to retrieve data from a REST API call and display it as a list using Handlebars, which functions as my view engine in a Node Express App.

Below is the route I am using:

router.get('api/projects', function(req, res){

    Project.find(function(err, projects){
        if(err)
            res.send(err);

        console.log(projects);

        res.render('list-view', projects);
    });
});

The JSON array "projects" contains various projects with keys for Name and _id.

Here is the HTML code in list-view.hbs:

{{#each .}}

<div class="thumbnail">
  <div class="caption">
    <h5> Name: {{name}} </h5>
  </div>
</div>

{{/each}}

My issue lies in the fact that even though my list-view page correctly displays the projects in a list format as intended, it always shows a few empty projects at the end of the list. I am perplexed as to why this is happening. For instance, if I have 8 projects in the "projects" array, my page will render all 8 correctly but display 11 in total due to the extra empty projects. Despite confirming that there are only 8 projects in the array using console.log(projects), the extras persist. Any insights into why this is occurring?

Answer №1

I finally found the solution to this issue. The key was to pass the projects JSON Array to handlebars as a single object:

router.get('/api/projects', function(req, res){

    Project.find(function(err, projects){
        if(err)
            res.send(err);
        res.render('list-view', {projects: projects});
    });
});

With that in place, my #each helper now looks like this:

    {{#each projects}}
    <div class="thumbnail">
      <div class="caption">
       <h5> Name: {{name}} </h5>
      </div>
    </div>
    {{/each}}

Thanks to this adjustment, the list now displays correctly.

Answer №2

Regarding the solution provided:

When you have the code snippet

  • res.render('list-view', {projects: projects})
    in your JavaScript file and
  • {{#each projects}} in your Handlebars template,

it is essentially the same as having

  • res.render('list-view', projects)
    in your JavaScript and
  • {{#each .}} or {{#each this}} in your Handlebars template.

You may be facing an issue because you are passing an object from the API that contains all serializable properties.

Try using the following approach instead:

res.render('list-view', projects.get());

The .get() method will only return the array that is relevant for our use.

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 way to update the state of the backend (true, false) for toggling in React.js?

I am developing a React.js application to manage household appliances from the front-end side. My main goal is to synchronize the toggle button with the backend state. The sensor device has a property called "armed." I want the toggle button to show ON w ...

Ways to switch out the background image using jQuery

I am currently using jQuery to dynamically change the background image of a web page. Right now, I have implemented two separate buttons that toggle between Image A and Image B. By default, Image A is displayed on the page. My goal is to enhance this func ...

I am facing an issue with my if statement not functioning properly when verifying a radio input

Trying to validate radio input to confirm if it's the correct answer, but encountering an issue where it skips the line if (answer == allQuestions[q].correctAnswer). Here is the complete code: https://jsfiddle.net/alcatel/sopfmevh/1/ for (let k = 0; ...

Error caused by Gson Overflow

While attempting to convert a Json string into a Java object using the Gson library, I encountered a StackOverflowException. java.lang.StackOverflowError com.google.gson.internal.$Gson$Types.checkNotPrimitive($Gson$Types.java:431) com.google.gson ...

"Obtaining a URL that begins with using jQuery: A Step-by-

How can I extract the full URL that starts with http://sin1.g.adnxs.com Here is the code snippet: <div id="testingurl"> <div class="ads98E6LYS20621080"> <!-- This script is dynamically generated --> <iframe src="http://testing ...

Challenges with inferring return values in Typescript generics

I'm encountering an issue with TypeScript that I'm not sure if it's a bug or an unsupported feature. Here is a Minimal Viable Example (MVE) of the problem: interface ColumnOptions<R> { valueFormatter(params: R): string; valueGette ...

The promise of a MongoDB connection with Node.js returns as 'awaiting fulfillment'

Greetings to all! A few weeks ago, I embarked on the journey of learning javascript, node.js and mongo. As a beginner, I have an interesting task at hand today. My goal is to add a simple document to the mongoDB and perform a conditional check. So here&apo ...

Using jQuery to dynamically add a value to a comment string

Is there a way to dynamically include tomorrow's start and end times in the message for the setupOrderingNotAvailable function if today's end time has passed? The current message states that online ordering will be available again tomorrow from 1 ...

Ways to properly link a webpage using the anchor tag's href attribute

I am currently working with reactjs and bootstrap, and I am trying to display and collapse an unordered list within a list item (nested unordered list). Bootstrap provides a useful collapse feature for this purpose. By using an anchor tag with a data-toggl ...

I noticed that when I use jQuery to add a class to an <li> element, the class is added successfully but then quickly removed. I'm wondering if this could be a conflict with

$(document).ready(function() { var $listItems = $('ul li'); listItems.click(function() { $listItems.removeClass('selected'); $(this).addClass('selected'); }); }); .selected{ background color: "green"; } / ...

Execute a simulated click function in JavaScript without causing the viewport to move

I have successfully implemented a sticky add to cart feature on my Shopify store. However, there seems to be an issue where clicking on the variations in the sticky area also triggers the same variations on the product page, making it difficult for users t ...

Retrieving Image from Link for Django Web Application

My JSON file contains the following data: "Product_url": "https://www.amazon.in/Samsung-Galaxy-Storage-Additional-Exchange/dp/B07PQ7CRBH/ref=sr_1_11?keywords=phone&qid=1563166792&s=electronics&smid=A14CZOWI0VEHLG&sr=1-11&quo ...

Run an Angular application and an ExpressJS endpoint on a server hosted on AWS EC2

As a newcomer to the world of NodeJS, Angular, and Express, I must admit that I am still learning the ropes. I recently started working on a project that involves creating a website using AngularJS with server-side logic in ExpressJS. However, as I delve ...

What is the best way to divide text into key-value pairs using JavaScript?

I have data in text format from my Raspberry Pi that I need to insert into MongoDB as key-pair values or JSON for my Node.js Application. I'm relatively new to JavaScript and I'm looking for a solution. Any suggestions would be greatly appreciate ...

Having trouble retrieving specific values from my node.js mongoose model, only getting the entire object returned

After spending the last 4 hours working on this, I'm in need of some assistance. I am trying to access specific values in my database, such as response.data.values.imglink, but when I add imglink within console.log(), it returns undefined. I can retri ...

A more Pythonic approach to managing JSON responses in Python 2.7

Currently, I am using Python 2.7 to fetch JSON data from an API. Here is the code snippet I have been working on: import urllib2 URL = "www.website.com/api/" response = urllib2.urlopen(URL) data = json.load(response) my_variable = data['location&apo ...

confirmation box for deleting a row in a grid view

I am looking to enhance the delete confirmation box on my Gridview delete function. Currently, I am using a basic Internet Explorer box for confirmation but I want to display a more stylish confirmation box. Here is the JavaScript code snippet within my gr ...

Trouble getting CSS and JavaScript to function properly with HTTPS?

It seems that the css and js files are functioning properly on , but not on . As a novice in web design and javascript, I am struggling to find a solution to this issue. Trying to link the CSS file with "//isdhh.org/css/style.css" has not resolved the pr ...

In Java, what is the process of converting a string in the format {a=2 ,b=5} to a JSON object in the format {"a":2 , "b":5}?

I have received the outcome as {a=2 ,b=5} following the evaluation of a SpEL expression. I would like to convert it into json format. Can anyone provide guidance on how to achieve this? Your assistance is greatly appreciated! ...

Utilizing AJAX in ASP.net Web API 2 to send and receive JSON data efficiently

net Web API 2. I want to send a JSON string to one of my POST functions and receive JSON back. My AJAX: $("#btnPost").click(function (event) { var sqlQ = "SELECT TOP 50 LTRIM(RTRIM(REPLACE(OID, ' ', ''))) FROM vwPS_DAT WHERE OID != & ...