【问题标题】:Mongoose modify single field from .find() responseMongoose 从 .find() 响应中修改单个字段
【发布时间】:2020-11-12 04:06:57
【问题描述】:

我正在尝试修改 .find() 中单个字段的结果以删除不必要的数据。 字段likedBy(数组)在不包含用户ID 时应返回一个空数组。但是,当likedBy 确实包含 userId 时,它应该返回仅包含该 userId 的数组,而不是所有 userId。

const response = await MyObject.find().lean({
    "likedBy": {
        "$elemMatch": {
            "$eq": body.userId
        }
    },
});

userId = 'id-1' 时的当前响应:

{
    "_id": "some id",
    "...rest of the fields"
    "likedBy": [
        "id-1",
        "id-2",
        "id-3",
    ]
},

我想要什么:

{
    "_id": "some id",
    "...rest of the fields"
    "likedBy": [
        "id-1",
    ]
},

【问题讨论】:

  • 为什么不将此.forEach(doc=> doc.likedBy.includes(body.userId) && doc.likedBy=body.userId); 附加到您的电话中。不过,您将发送更多位。但这可能更快。
  • 那绝对可行,但我认为如果可能的话,直接使用猫鼬会更好。
  • 好吧,由你决定。对我来说,你只需要一个简单的解决方案。管道往往很慢。但解决方案越多越好。

标签: node.js mongodb mongoose


【解决方案1】:

您可以定义一个aggregate 管道并使用$filter 只返回匹配的数组元素:

YourModel.aggregate([
  {
    $match: {
      "likedBy": body.userId
    }
  },
  {
    $project: {
      likedBy: {
        $filter: {
          input: "$likedBy",
          as: "likedBy",
          cond: {
            $eq: [
              "$$likedBy",
               body.userId
            ]
          }
        }
      },
      otherField: 1         
    }
  }
])

这是mongoplayground 的示例。

【讨论】:

  • 感谢您的帮助,这几乎就是我想要的。如果我正确使用它,那么当 userId 不匹配时(例如,当 userId = 'id-10')时,这将不返回任何内容,而我仍想返回具有所有字段的所有对象,并且只返回 likeBy 字段为 null 或找不到 userId 时的空数组。
猜你喜欢
  • 2017-08-11
  • 1970-01-01
  • 2015-10-08
  • 2018-11-05
  • 2020-06-07
  • 2018-12-28
  • 2020-05-16
  • 2014-10-03
  • 2018-10-02
相关资源
最近更新 更多