【问题标题】:$Filter with mongoDB on documents inside array$Filter 与 mongoDB 对数组内的文档进行过滤
【发布时间】:2020-01-28 21:53:43
【问题描述】:

我正在尝试构建一个查询以从我的 mongoDB 中获取信息,但我需要过滤结果并仅获取相应的值。

这是我迄今为止尝试过的方式。我需要将 costsHouse._id 与我将在链接中传递的 id 匹配。

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

以下屏幕是 mongodb 架构。 我需要从 costsHouse 中获取每个值,但只有我通过的“id”才需要与 costsHouse.ID 匹配

得到结果后,我需要在车把中使用它们

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

【问题讨论】:

  • expensesHouse 需要包裹在 $project 阶段
  • 我得到这个结果:[ { _id: 5e2dea5f71cbdd1a6dd1c8fc, costsHouse: [] }, { _id: 5e2debbf30b9cd1aa5aca711, costsHouse: [] }, { _id: 5e2f57ad63e463338bc44f9a, costs: 5e2f5b3163e463338bc44f9c, costsHouse: [] } ] 这是我所有的房子,但没有给我正确的费用。
  • 我猜你应该使用ObjectId 对象而不是传递string

标签: node.js mongodb mongodb-query handlebars.js


【解决方案1】:

试试这些选项:

1) 使用$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) 使用$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
        });
    })
})

【讨论】:

    【解决方案2】:

    根据您所说,您正在尝试实现运营商 $elemMatch 为您提供的功能。

    试试这段代码,如果有帮助,请在下方评论:

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

    【讨论】:

    • $elemMatch 从我的数组中获取所有值,而不是特定的值..
    • 这不是 elemMatch 实际工作的方式,问题是您使用的是 objectId,不是吗?如果是,您需要使用 _id: ObjectId(req.params.id) 。判断这种方式是否有效
    • 我在这里测试过,它可以工作,我什至更新了答案以支持这种方式
    • 我已经用 $elemMatch: _id: ObjectId(req.params.id) 更新了我的查询和搜索,但它仍然检索所有费用,而不仅仅是特定的 id
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 2022-01-11
    • 2018-08-08
    • 2014-05-16
    相关资源
    最近更新 更多