Carlos Orelhas
Carlos Orelhas

Reputation: 73

Get Specific Object from Array in MongoDB collection into handlebars table

I'm trying to build a table with values from an Array of objects from mongodb, but I only can get every value and only need the specific value.

So I made a query like this

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
    });
  });
});

I want to retrieve the specific value from expensesHouse with status 'Private'.

And in handlebars I have this structure

<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>

And after this handlebars, this is the result

Result

The Schema structure is the follow MongoDB structure

So I want to show in the web page the value from expensesHouse with the Status 'Private'.

How can I change my code to retrieve only this value ?

Upvotes: 1

Views: 205

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

Please update your code with the below, it resolves your issues with code & also with query :

router.get("/arquiveExpense", ensureAuthenticated, async (req, res) => {
    try {
        let house = await House.findOne({ // You can use findOne as if userID is unique
            userID: req.user.id
        }, { expensesHouse: { $elemMatch: { status: "Private" } } }) //$elemMatch in projection helps you to get what is needed
        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)
    }
})

Upvotes: 1

Related Questions