How to update data present in nested

const postSchema = mongoose.Schema({
  userId: { type: String, required: true },
  username: { type: String, required: true },
  
  comments: { type: [{ postedBy: String, comment: String }] },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

How to update comments of a particular user using node js

const post = await DevPost.findByIdAndUpdate(
    req.params.postId,
    {
      $set: { comments: { _id: req.params.commentId, postedBy: req.body.postedBy,
        comment: req.body.comment } },
    },
    { new: true }
  );

I tried this but it drops all the comment and create new one

Hi,

You can use positional $ operator. In order to use it, you have to specify filter for an array inside the query object. In this case, it would be "comments.postedBy": user_id. After that, if you use positional $ operator in update object, it would update only array elements that matched the query part.

You can do it like this:

db.collection.update({
  "_id": 1,
  "comments.postedBy": 1
},
{
  "$set": {
    "comments.$.comment": "New Text 1"
  }
},
{
  "new": true
})

Working example

1 Like

Yes it does the stuff, one small query if we have to update data present in nested part

const postSchema = mongoose.Schema({
  tags: { type: String, required: true },
  comments: {
    type: [
      {
        postedBy: String,
        comment: String,
        time: { type: Date, default: Date.now },
        replies:[{
          cid:String,
          postedBy:String,
          replymsg:String,
          time: { type: Date, default: Date.now },
        }]
      }
    ],
   
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

how can I update the replymsg field here

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.