0

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

1 Answer 1

1

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"
          ]
        }
      }
    });
Sign up to request clarification or add additional context in comments.

12 Comments

Why code runs on the playground but not in my project? Do you know any reason? There is no error message, just run but no changes in my document
What version of mongoose are you using? And what is the exact mongoose query? Please share it, here
im using mongoose 6.3.4 here is my code await Post.updateOne( { postId: postId, comments: { $elemMatch: { id: commentId, }, }, }, { $push: { "comments.$.replies": { $each: [ { id: new mongoose.Types.ObjectId(), user: req.user, content: req.body.reply__content, }, ], }, }, } )
Try this query and check whether it returns anything or not. await Post.findOne({ postId: postId, comments: {$elemMatch: { id: commentId}}})
Thank you so much for supporting me That query just return null for some reason
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.