【问题标题】:Get access to the "current element" when traversing a mongoDB (mongoose) array遍历 mongoDB (mongoose) 数组时访问“当前元素”
【发布时间】:2022-01-10 16:45:29
【问题描述】:

我有一个“类似帖子的社交媒体”的猫鼬模型(称为 PostModel),它具有以下架构:

{
  caption: String,
  comments: [
    {
      comment: String,
      // basically an array to store all those who liked the comment
      likedBy: [...] // array of references to a different model
    },
    ... // more comment objects like this
  ]
}

我只是想知道在查询帖子时每条评论获得的点赞数。这不应该像现在这样烦人和困难。我在这上面花了 4 个多小时。

到目前为止我所尝试的:

尝试 1:

PostModel.findById(postId, {
  "comments.likes": { $size: "$comment.likedBy" } // gives the number of comments instead of the number of likes on the comment
})

尝试 2:

PostModel.findById(postId, {
  "comments.likes": { $size: "$likedBy" } // gives "likedBy not defined" error
})

尝试 3:

PostModel.findById(postId, {
  "comments.likes": { $size: "$comments.$likedBy" } // gives "FieldPath field names may not start with '$'. Consider using $getField or $setField" error
})

尝试 4:

PostModel.findById(postId, {
  "comments.likes": { $size: "$comments.$.likedBy" } // gives "FieldPath field names may not start with '$'. Consider using $getField or $setField" error
})

我基本上想在这个“forEach”之类的数组遍历中访问“当前元素”。例如:

const a = [{likes: ["x", "y"]}, {likes: ["a", "b"]}, {likes: []}];
a.forEach((element, index) => {
  console.log(element.likes.length) // this is what I want but for mongoDB
})
// output: 2 2 0

我到处寻找,但即使搜索了 4 个小时也找不到解决方案。任何能让我远离当前方向的东西都会有所帮助。

我不想将整个 cmets 数组加载到内存中,只是为了获取嵌套 likeBy 数组的长度。否则这甚至都不是问题。

【问题讨论】:

    标签: javascript node.js mongodb mongoose nosql


    【解决方案1】:

    如果您想从所有comments 中获取总喜欢数,您可以使用$reduce 运算符:

    {
        $project: {
            likes: {
                $reduce: {
                    input: "$comments",
                    initialValue: 0,
                    in: { $add: [ "$$value", { $size: "$$this.likedBy" } ] }
                }
            }
        }
    }
    

    Mongo Playground

    或者,您可能需要$map 为每条评论添加许多赞:

    {
        $project: {
            comments: {
                $map: {
                    input: "$comments",
                    in: {
                        $mergeObjects: [
                            "$$this",
                            { $numberOfLikes: { $size: "$$this.likedBy" } }
                        ]
                    }
                }
            }
        }
    }
    

    Mongo Playground

    【讨论】:

    • 是的。确实是这样。我正在寻找“$$this”“运营商的东西”。我实际上不知道它的存在,所以谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 2021-10-26
    • 2013-06-23
    • 2011-04-18
    • 2013-12-18
    • 2023-03-08
    相关资源
    最近更新 更多