MongoDB - 使用聚合管道评论赞成/反对

我正在尝试为评论实现赞成/反对票机制(类似于 reddit 上的赞成/反对票机制).我有一个名为 commentReputation 的单独集合,其中的文档可能如下所示:

I'm trying to implement an upvote/downvote mechanism for comments (similar to the upvoting/downvoting mechanism found on reddit). I have a separate collection called commentReputation and the documents inside can look like this:

{
    "_id" : ObjectId("5e5acb6d6034a879655c8819"),
    "commentId" : ObjectId("5e5983102328a83d1a4b541f"),
    "creationDate" : ISODate("2020-02-29T20:37:01.509Z"),
    "upvotes" : [
        ObjectId("5e5983102328a83d1a4b53e7"),
        ObjectId("5e5983102328a83d1a4b53e4")
    ],
    "downvotes" : [
       ObjectId("5e5983102328a83d1a4b53e5")
    ]
}

简而言之:每条评论最终都会有它自己的 CommentReputation 文档(应该在有人支持/反对评论时立即创建 CommentReputation 文档)

In short: every comment will eventually have it's own CommentReputation document (the CommentReputation document should be created as soon as someone upvotes/downvotes a comment)

有两种情况:

  1. 集合是空的,这意味着我需要使用给定的 commentId x 创建我的第一个 CommentReputation 文档.在项目的其他部分中,我使用 $setOnInsert{ upsert: true } 但似乎(查看文档)聚合管道不支持 $setOnInsert 和现在一样.有没有其他方法可以解决这个问题?

  1. The collection is empty meaning that I need to create my very first CommentReputation document with a given commentId x. In some other part of the project I was using $setOnInsert with { upsert: true } but it seems (looking at the documentation) that the aggregation pipeline does not support $setOnInsert as for now. Is there another way to deal with this problem?

文档就在那里,应该会进行实际的投票.

The document is there and the actuall upvoting should occur.

a) upvotesdownvotes 数组都不包含试图投票的 userId,因此它被添加到 upvotes 数组,无需任何进一步操作

a) Both upvotes and downvotes arrays do not contain the userId that is trying to upvote thus it gets added to the upvotes array without any further actions

b) upvotes 数组包含 userId 试图对评论进行投票,结果 userId 应该从 upvotes 数组.(用户已经对此评论点赞并再次点击取消点赞的点赞按钮)

b) The upvotes array contains the userId that is trying to upvote the comment as a result the userId should be REMOVED from the upvotes array. (the user already had this comment upvoted and clicked a second time the upvote button which cancels out the upvote)

c) downvotes 数组包含 userId.在这种情况下,应该从 downvotes 中删除 userId 并添加到 upvotes

c) The downvotes array contains the userId. In this case the userId should be removed from downvotes and added to upvotes

我正在尝试使用 updateOne 方法和聚合管道来完成上述逻辑,但是我不确定这是否可能.

I'm trying to accomplish the above logic with the updateOne method and a aggreagtion pipeline however I'm not sure if this is even possible.

我目前拥有的是返回一个 "Unrecognized pipeline stage name: '$cond'"

What I currently have is returning a "Unrecognized pipeline stage name: '$cond'"

const updateUpvotes = {
  $cond: {
    if: { $elemMatch: { upvotes: ObjectID(userId) } },
    then: { $pull: { upvotes: ObjectID(userId) } },
    else: { $addToSet: { upvotes: ObjectID(userId) } }
  }
};

db.collection(collectionName).updateOne({
   commentId: ObjectID('5e5983102328a83d1a4b541f')
}, [updateUpvotes])

我是否过度考虑了整个功能?我想 1. 问题可以通过简单地创建一个 CommentReputation 文档来解决(使用空的 upvotesdownvotes 在在创建 Comment 文档的同时.

Am I overthinking the whole feature? I guess the 1. problem can be solved by simply creating a CommentReputation document (with empty upvotes and downvotes at the same time the Comment document is being created.

有没有更好的方法来做到这一点?我希望它在单个查询请求中工作.也许你们中的某个人实现了类似的功能,可以给我一些提示.

Is there a better way of doing this? I would love to have it working inside a single query request. Maybe someone of You guys implemented a similar feature and can give me some hints on this one.

推荐答案

您可以通过以下管道更新来做到这一点,但它需要存在 upvotes 和 downvotes 数组.即使它只是空的.

you can do it with the following pipeline update but it requires that the upvotes and downvotes arrays exist. even if it's just empty.

var comment_id = ObjectId("5e5983102328a83d1a4b541f");
var user_id = ObjectId("5e5983102328a83d1a4b53e5");

db.commentReputation.update(
    {
        commentId: comment_id
    },
    [
        {
            $set: {
                upvotes: {
                    $cond: [
                        { $in: [user_id, '$upvotes'] },
                        { $setDifference: ['$upvotes', [user_id]] },
                        { $setUnion: ['$upvotes', [user_id]] }
                    ]
                }
            }
        },
        {
            $set: {
                downvotes: {
                    $cond: [
                        { $in: [user_id, '$downvotes'] },
                        { $setDifference: ['$downvotes', [user_id]] },
                        '$downvotes'
                    ]
                }
            }
        }
    ]
);

相关文章