我如何将新元素推入子文档中Post> Comments> Replies> likes as a array

时间:2019-10-28 11:31:01

标签: node.js mongodb express mongoose aggregation-framework

我有一个样本Post集合

[{
    "_id" : ObjectId("5da832caeb173112348e509b"),
    "body" : "Lorem Ipsu.",
    "comments" : [ 
        {
            "comment" : "my sample comment",
            "_id" : ObjectId("5db06e11d0987d0aa2cd5593"),
            "replies" : [ 
                {
                    "likes" : [ 
                        "5d999578aeb073247de4bd6e", 
                        "5da85558886aee13e4e7f044"
                    ],

                    "_id" : ObjectId("5db6a88f7c6cfb0d0c2b689b"),
                    "reply" : "my reply to this comment",
                    "user" : "5da85558886aee13e4e7f044"
                }
            ],

            "likes" : [ 
                "5da85558886aee13e4e7f044",
            ]
        }, 

    ],

}]

要将addremove元素转换为comments.likes$push$pull,可以使用以下操作。

   Post.updateOne(
     {_id: req.body.id_post, "comments._id": req.body.id_comment},
     { $push: {"comments.$.likes": req.user._id}});

但是,如果我想push进入replies.likes,请问有人可以帮我吗?

我已经尝试过类似的操作,但是replies.likes尚未更新。

 db.posts.updateOne(
    { "comments.replies._id": Object("5db6a88f7c6cfb0d0c2b689b") },
    { "$push": { "comments.0.replies.$.likes": Object("5db6a88f7c6cfb0d0c2b689a") } },
    function(err,numAffected) {
       // something with the result in here
    }
);

1 个答案:

答案 0 :(得分:1)

您可以使用数组过滤器:

db.getCollection("test").updateOne(
  {
    "comments.replies": {
      "$elemMatch": {
        "_id": Object("5db6a88f7c6cfb0d0c2b689b")
      }
    }
  },
  { "$set": { "comments.$[outer].reply.$[inner].likes": Object("5db6a88f7c6cfb0d0c2b689a") } },
  {
    "arrayFilters": [
      { "outer._id": ObjectId("5cd26a886458720f7a66a413") },
      { "inner._id": ObjectId("5cd26a886458720f7a66a415") }
    ]
  }
)

不要介意ID