nevicoder
nevicoder

Reputation: 1

push object into nested array with mongoose

im new to mongodb and im having a problems. I have a document like this

[
    {
    _id: "post1",
    content: "post1 content",
    comments: [
    {
      id: "comment 1",
      user:"user comment",
      replies:[]
    },
    {
      id: "comment 2",
      user:"user comment",
      replies:[]
    }
        ]
    },
{
    _id: "post2",
    content: "post2 content",
    comments: [
    {
      id: "comment 1",
      user:"user comment",
      replies:[]
    },
    {
      id: "comment 2",
      user:"user comment",
      replies:[]
    }
        ]
    }
]

How can i put new object into replies? I got the postid and commentid i need

Upvotes: 0

Views: 72

Answers (1)

Charchit Kapoor
Charchit Kapoor

Reputation: 9284

Use $elemMatch operator to match your specific comment in a post, and then push the reply into the replies array using $push. Like this:

db.collection.update({
  _id: "post1",
  comments: {
    $elemMatch: {
      id: "comment 1"
    }
  }
},
{
  "$push": {
    "comments.$.replies": {
      "$each": [
        "value1",
        "value2"
      ]
    }
  }
})

Here is the playgrounf link.

In mongoose it can be achieved like this:

await CollectionName.updateOne({
      _id: "post1",
      comments: {
        $elemMatch: {
          id: "comment 1"
        }
      }
    }, {
      "$push": {
        "comments.$.replies": {
          "$each": [
            "value1",
            "value2"
          ]
        }
      }
    });

Upvotes: 1

Related Questions