0

I have this Mongoose query:

Posts.updateOne({  _id: fields.opin_id, "comments._id" : 
fields.comment_id, "comments.user_id" : fields.user_id}, {$set: 
{"comments.$.body" : fields.comment } },......

Where comments is part of an array. What I am trying to do is match one element of the array by both comment_id, and user_id, but when I update said array, it is always the first element with user_id being updated. comments._id is ignored. I already tried

$and: [{"comments._id" : 
    fields.comment_id}, {"comments.user_id" : fields.user_id}]

What am I doing wrong?

Rajan Sharma
  • 2,211
  • 3
  • 21
  • 33
Roddy P. Carbonell
  • 858
  • 1
  • 11
  • 16

1 Answers1

0

If I understood you correctly your comments field on the main model is essentially an array of objects like this:

comments = [
 {
 _id: 'firstComment',
 body: "AAA"
 },
 {
  _id: 'secondComment'
  body: 'BBB',
 }] 

If that's the case what you want to use is $elemMatch. Here are the Mongo docs. Your query will look like this:

Posts.updateOne({  _id: fields.opin_id, 
comments: { $elemMatch: {_id : fields.comment_id, user_id : fields.user_id}}}, 
{$set:{...}})
Alex D
  • 970
  • 6
  • 13