Mongo update query for modifying array field failing

Viewed 53

Important: Mongo Version I am using 3.4 Just Found out array filters is not available in 3.4

Any suggestion would be appreciated.

I have been trying this for days now I am trying to update particular comment text inside document. My document looks like this:

{
  _id: "6ff1...<alphanumeric Id>",
  name: "T-00001",
  comment: [
   {
     _id: "6f7123....<alphanumeric Id>",
     author: "6fsd...<alphanumeric Id pointing to user schema>"
     text: "Hello",
     edited: false
   },
   {
     _id: "6f75323....<alphanumeric Id>",
     author: "6ffgh21...<alphanumeric Id pointing to user schema>"
     text: "Second Comment",
     edited: false
   }
 ]
}

What I am trying to achieve is to edit comment text here of particular comment id what my update query looks like is :

db.story.update(
  { _id: mongoose.Types.ObjectId(storyId) },  // Find that story story Id coming from body
  {
    $set : {
    "comment.$[elem].text": "Update text with this",
    "comment.$[elem].edited": true
    }
  },
  { "arrayFilters": [
     { "elem._id": mongoose.Types.ObjectId(commentId),
       "elem.author": mongoose.Types.ObjectId(authorId)
     } // Update only that comment.. Ids here coming from body   
     
  ]}
)

Error Message I am getting

"errmsg" : "cannot use the part (comment of comment.$[elem].text) to traverse the element ({comment: [ { posted: new Date(1633092292670), delStatus: 0, _id: ObjectId('615702c4de4cf17dab996b4f'), by: \"User\", author: ObjectId('60ab52b1a3aa844774ca0fb3'), text: \"hello7\", edited: true }, { posted: new Date(1633699486732), delStatus: 0, _id: ObjectId('6160469e8aca585d3909708c'), by: \"User\", author: ObjectId('60ab52b1a3aa844774ca0fb3'), text: \"2021-10-08T13:24:46.671Z\" } ]})"
1 Answers

Found the solution god I am so bad....

db.story.update(
    {
        $and: [
            { _id: mongoose.Types.ObjectId(storyId)},
            { "comment._id": mongoose.Types.ObjectId(commentId)},
            { "comment.author":  mongoose.Types.ObjectId(authorId)}
        ]
    },
    {
        $set: {
            "comment.$.text": body.text,
            "comment.$.edited": true
        }
    }
)

With this I have a big problem whenever I hit this query it is updating some other comment until I remove the line:

{ "comment.author":  mongoose.Types.ObjectId(authorId)}

Can someone please help?

Related