Retrieve a particular item from an array within a MongoDB collection and display it in a handlebars table

I am facing a challenge in building a table with values from an Array of objects retrieved from mongodb. I am able to fetch every value, but I actually only need a specific value.

Here is the query I have constructed:

router.get("/arquiveExpense", ensureAuthenticated, (req, res) => {
  House.find({
    userID: req.user.id,
    expensesHouse: { $elemMatch: { status: "Private" } }
  }).then(house => {
    console.log(house);
    res.render("houses/arquiveExpense", {
      house: house
    });
  });
});

My objective is to extract the specific value from the 'expensesHouse' with status 'Private'.

In my handlebars file, the structure looks like this:

<tbody>

                    <tr>
                        {{#each house}}

                        <td>{{expenseType}}</td>
                        <td>{{price}}€</td>
                        <td>{{payAt}}</td>

                        <td>{{formatDate date 'MMMM Do YYYY'}}</td>
                        <td>
                            <a href="/houses/showExpense/{{id}}" id="detailsExpense"
                                class="btn btn-outline-light mb-3"><i class="fas fa-eye mr-2"></i>Details
                            </a>
                        <td>
                            <a href="/houses/editExpense/{{id}}" id="editExpense" class="btn btn-outline-light mb-3"><i
                                    class="fas fa-edit mr-2"></i>Edit
                        </td>
                    </tr>

                    {{else}}
                    <p>No expenses</p>
                    {{/each}}
                </tbody>

Upon rendering the handlebars template, the output can be viewed here.

The Schema structure is as depicted here.

My goal is to display on the web page the value from 'expensesHouse' with the Status 'Private'.

How can I modify my code to retrieve this specific value only?

Answer №1

To resolve the issues in your code and query, please incorporate the following updates:

router.get("/arquiveExpense", ensureAuthenticated, async (req, res) => {
    try {
        let house = await House.findOne({ // Utilize findOne due to userID uniqueness
            userID: req.user.id
        }, { expensesHouse: { $elemMatch: { status: "Private" } } }) //$elemMatch in projection helps retrieve necessary data
        if (house) { // .findOne() returns null if no document found, else an object
            console.log(house);
            res.render("houses/arquiveExpense", {
                house: house
            });
        } else { // No document found
            console.log('No house found')
        }
    } catch (error) {
        console.log('Error at DB call ::', error)
    }
})

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

One MongoDB replica where writes are directed to a single server

I'm currently developing a node.js application that involves managing 2 servers. One server is designated as the production server, while the other is known as the dataAnalytics server. At the moment, all data is being stored in collections within th ...

Steps to remove a scrollbar from a fullscreen slider

Can anyone provide code examples on how to disable the scroll bar on a full screen slider? I want to have a scroll down button on each slider that, when clicked, will show the scrollbar only below the slider. I don't want the scrollbar to be visible ...

Step-by-step guide to creating a dynamic button that not only changes its value but also

I am trying to implement a translation button on my website that changes its value along with the text. Currently, I have some code in place where the button toggles between divs, but I am struggling to make the button value switch as well. Given my limit ...

Listening for time events with JQuery and controlling start/stop operations

I recently developed a jQuery plugin. var timer = $.timer(function() { refreshDashboard(); }); timer.set({ time : 10000, autostart : true }); The plugin triggers the refreshDashboard(); function every 10 seconds. Now, I need to halt the timer for ...

Troubleshooting: jQuery AJAX request not functioning as expected

function showDialog(link) { $('#dialog .newsletter-join').click(function() { email = $.trim($(this).parent().find('.email').val()); if (email != "Email Address" && email.length > 5) { $.ajax({ ...

Manipulate the dimensions of an item in Three.js

I am a beginner in Three.js and I am looking to create a 3D scene with multiple objects floating in the sky and a scale displayed on the screen. The scale should be movable up and down to bring the objects closer or further away, creating the illusion of ...

MongoDB Schema Design: Embrace the Advantages of Embedding vs

Imagine I am creating a platform similar to Foursquare that monitors user check-ins based on their location, utilizing MongoDB as the backend database. In this scenario, users can check-in at different locations, resulting in collections within the schema ...

How to merge data from various APIs in React and display it on the screen

I am currently working on fetching data from multiple APIs and rendering it. I have successfully written the code to retrieve the data, but I am facing an issue with populating the nested array format of the data into my state for interpolation. Since th ...

Updating variable values in AngularJS while navigating through routes

How can I dynamically set the flag icon inside the page header based on the selected language using AngularJS? The language selection is done in a separate .htm file and all managed by AngularJS routing. My application has a single controller called "appCo ...

How do I access Google Chrome and perform a Google image search within a Node.js/Electron program?

I am currently working on incorporating Google Image search into my Electron-based photo application. My goal is to have users click on a button labeled "Search Google for Image," which will then open up Chrome (if installed) with the local image file in ...

Encountering trouble with displaying data in Express and Mongoose

Struggling to comprehend how to define and utilize an API in Express, while using Mongoose to connect with MongoDB. Successfully saving objects from input on the front end, but getting lost when it comes to retrieving and displaying the saved data. Take a ...

Endless flowing river of Baconjs

I'm working on a script that retrieves values from a Redis list and outputs them to the console. Below is the code I am using: var redis = require("redis"), client = redis.createClient(); Bacon = require('baconjs'); Bacon.repeat(fu ...

Emphasize sections of text within a chart

Looking for a Specific Solution: I've encountered similar problems before, but this one has a unique twist. What I'm trying to achieve is to search for a substring within a table, highlight that substring, and hide all other rows (tr's) th ...

Error: The 'in' operator cannot be used to search for '_id' within the male

Hey there, I'm encountering an issue with the new versions of node.js. Previously, I had code that looked like this: label(for='user_sex') Sex: select(id='user_sex', name='user[sex]') option(id='user_male' ...

Error: Attempting to access the 'state' property of an undefined variable within the bootstrap framework

While attempting to update the state value, I encountered an error stating TypeError: Cannot read property 'state' of undefined. This error occurs when I enter something in a field and then click submit. As a newcomer to React, I realize this may ...

Developing a unique attribute using AngularJS

As a beginner in AngularJS, I am experimenting with creating directives to manipulate the background-color of a <div> based on specific conditions. I aim to write code like this within my view: <div effect-color="#2D2F2A">content here</div& ...

What are the steps for creating an animated visualization of the peak chart?

As a newcomer to CSS and Javascript, I am currently struggling with animating a peak (bar) chart that I came across on codepen. If anyone can provide assistance or guidance, it would be greatly appreciated! The chart can be found here: http://codepen.io/An ...

Interpolating backticks in Javascript allows for constructing a URL containing empty spaces

When utilizing string interpolation with backticks to construct a URL that sends data to a django endpoint, the resulting URL contains unnecessary whitespace and a new line. The problematic JavaScript code is as follows: (function (window, document, unde ...

Unable to locate the 'isDirectory' property of an undefined value

This code example is showcased in the book titled SMASHING Node.js:Javascript Everywhere. Despite following the steps and entering node index in the terminal, I encountered the following error message: Cannot read property 'isDirectory' of und ...

Currently, I am utilizing v-model to bind one input and name for the other. My main focus is on exploring the various methods for retrieving and manipulating their

I created a form with various input fields and upon submission, I am displaying the data in a modal. Although it functions correctly, I have concerns regarding the cleanliness of my code. Below is the simplified HTML structure: <div id="app"> < ...