Carlos Orelhas
Carlos Orelhas

Reputation: 73

$Filter with mongoDB on documents inside array

I'm trying to build a query to fetch information from my mongoDB but I need to filter the results and only get the corresponding value.

This is the way I have tried until now. I need to match the expensesHouse._id with the id i will pass in the link.

router.get("/showExpense/:id", ensureAuthenticated, (req, res) => {
  House.aggregate([
    {
      expensesHouse: {
        $filter: {
          input: "$expensesHouse",
          as: "each",
          cond: { $eq: ["$$each._id", req.params.id] }
        }
      }
    }
  ]).then(house => {
    console.log(house);
    res.render("houses/showExpense", {
      house: house
    });
  });

The following screen is the mongodb schema. I need to get every value from expensesHouse but only with the 'id' I pass need to match with the expensesHouse.ID

MongoDB Schema

After the result I need to use them here in my handlebars

<form>
                    {{#each house}}
                    {{#each expensesHouse}}
                    <div class="form-group">
                        <label for="expenseType" class="text-dark">Expense Type</label>
                        <input type="text" class="form-control" name="expenseType" value="{{expenseType}}" disabled>
                    </div>
                    <div class="form-group">
                        <label for="description" class="text-dark">Description</label>
                        <input type="text" class="form-control" name="description" value="{{description}}" disabled>
                    </div>
                    <div class="form-group">
                        <label for="price" class="text-dark">Price</label>
                        <input type="text" class="form-control" name="price" value="{{price}}" disabled>
                    </div>

                    <div class="form-group">
                        <label for="status" class="text-dark">Price</label>
                        <input type="text" class="form-control" name="status" value="{{status}}" disabled>
                    </div>
                    {{/each}}
                    {{/each}}
                </form>

Upvotes: 0

Views: 254

Answers (2)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

Try these options :

1) Use of $filter-aggregation :

var mongoose = require('mongoose');

router.get("/showExpense/:id", ensureAuthenticated, (req, res) => {
    var id = mongoose.Types.ObjectId(req.params.id);
    House.aggregate([
        {
            $addFields:
            {
                expensesHouse: {
                    $filter: {
                        input: "$expensesHouse",
                        as: "each",
                        cond: { $eq: ["$$each._id", id] }
                    }
                }
            }
        }
    ]).lean().then(house => {
        console.log(house);
        res.render("houses/showExpense", {
            house: house
        });
    })
})

2) Use of $elemMatch-projection :

    var mongoose = require('mongoose');

router.get("/showExpense/:id", ensureAuthenticated, (req, res) => {
    var id = mongoose.Types.ObjectId(req.params.id);
    House.find({ 'expensesHouse._id': id }, {
        members: 1, name: 1, description: 1, address: 1,
        type: 1, user: 1, userID: 1, userType: 1, expensesHouse: { $elemMatch: { _id: id } }, date: 1
    }).then(house => {
        console.log(house);
        res.render("houses/showExpense", {
            house: house
        });
    })
})

Upvotes: 1

Felipe Malara
Felipe Malara

Reputation: 1914

Based on what you said, you're trying to achieve what the operator $elemMatch provides for you.

Try this code and comment below if it helped:

.
. // All the other stuff
.
expensesHouse: {
    $elemMatch: {
        _id: req.params.id // or ObjectId(req.params.id)
    }
}

Upvotes: 0

Related Questions