1

I need to push an array inside a nested array.

I'm having post collection, inside that comments array is there, and inside the comments array replies array is there. i need the push values inside the likes array which is present inside the replies array

my collection structure is

"_id" : ObjectId("5a8dc1f67498b619070ed5bb"),   
"comments" : [
    {
        "created_at" : ISODate("2018-02-21T19:24:15.977Z"),

        "replies" : [
            {
                "created_at" : ISODate("2018-02-21T19:25:48.533Z"),
                "likes" : [
                    {
                        "created_at" : ISODate("2018-02-25T06:24:20.111Z"),
                        "_id" : 1
                    }

                ],
                "_id" : 1,
                "content" : "check 2nd"
            },
            {
                "created_at" : ISODate("2018-02-25T06:10:21.597Z"),
                "likes" : [
                    {
                        "created_at" : ISODate("2018-02-25T06:50:51.076Z"),
                        "_id" : 2
                    }
                ],
                "_id" : 2,
                "content" : "check reply reply"
            }
        ],
        "_id" : ObjectId("5a8dc75f1dc5601cb4e3fe5d"),
        "content" : "check 1st inner"
    },
    {
        "created_at" : ISODate("2018-02-21T19:26:04.569Z"),
        "likes" : [ ],
        "replies" : [
            {
                "created_at" : ISODate("2018-02-21T19:26:14.308Z"),
                "likes" : [ ],
                "_id" : ObjectId("5a8dc7d63ed5a01dbaa4c3b9"),\
                "content" : "check 3rd inner"
            }
        ],
        "_id" : ObjectId("5a8dc7cc3ed5a01dbaa4c3b8"),
        "content" : "check 3rd"
    }
],

i need to push values inside likes array whose reply _id is '2',

I already tried with this code,

module.exports.replyLike = function(body, userId, callback){
  const query = {
                _id: body.postId,
                "comments._id": body.commentId,
                "comments.replies._id":body.replyId
                };
  Post.update(query, {$push: {"comments.$.replies.$.likes": {userId: userId} } }, callback);
}

but it doesn't work,

if i give $push:{"comments.$.replies.1.likes"} it works, but want it do add dynamically. someone pointout the issue in my code and give a solution.

Jones Stephen
  • 473
  • 1
  • 5
  • 17

0 Answers0