1

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 ?

whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
Carlos Orelhas
  • 73
  • 1
  • 10
  • Does this answer your question? [How to search in array of object in mongodb](https://stackoverflow.com/questions/14040562/how-to-search-in-array-of-object-in-mongodb) – whoami - fakeFaceTrueSoul Jan 26 '20 at 19:31
  • I can retrieve the correct information from mongoDB, but I can't build the right information in handlebars. The problem is: After query mongoDB, the information I have is the correct, but when I pass them onto handlebars and see what I have on my page, I can't get the values there. – Carlos Orelhas Jan 26 '20 at 19:35
  • Is it because of not waiting until DB call is done ? Try this :: `router.get("/arquiveExpense", ensureAuthenticated, async (req, res) => { try { let house = await House.findOne({ userID: req.user.id, expensesHouse: { $elemMatch: { status: "Private" } } }) if (house) { console.log(house); res.render("houses/arquiveExpense", { house: house }); } else { console.log('No house found') } } catch (error) { console.log(error) } }) ` – whoami - fakeFaceTrueSoul Jan 26 '20 at 19:41
  • It works but gives me the same result I have.. The problem is in the handlebars since when I make a #each for everyone I get all expenses, public and private.. – Carlos Orelhas Jan 26 '20 at 19:55
  • You mean to say your query is filtering properly for a user based on `userID: req.user.id` but `expensesHouse` array has all statuses along with private ? – whoami - fakeFaceTrueSoul Jan 26 '20 at 19:57
  • Exactly! The query get me back both values, public, and privates. – Carlos Orelhas Jan 26 '20 at 20:03
  • @Carlor : That's why I've shared that MongoDB question link at first, anyhow please check my answer. – whoami - fakeFaceTrueSoul Jan 26 '20 at 20:05

1 Answers1

1

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)
    }
})
whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46