1

I am having trouble with the "$in" operator in Mongoose. At a high level I have a User schema, and one of the fields is an array of a Card schema. Within the Card schema there is a 'score' field. I would like to update the 'score' field based on a list of Card ids. Here is what I am trying to use:

User.updateMany(
  {
    "_id": userId,
    "cards._id": {
      "$in": cardIds
    }
  },
  { $inc: {"cards.$.score": 1 }},
  (err) => {console.log(err)}
)

When I run this code, only the first Card in the cardIds array is updated instead of all of them. Any idea why this isn't working? Thanks.

evan
  • 65
  • 8

1 Answers1

0

You need to use arrayFilters in .updateMany() , Try this query :

User.updateMany({
    "_id": userId
},
    { $inc: { "cards.$[element].score": 1 } },
    { arrayFilters: [{ "element._id": { "$in": cardIds } }] },
    (err) => {}
)
evan
  • 65
  • 8
whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
  • Tried this, but I'm not seeing any changes in my db. No errors, though... – evan Feb 27 '20 at 17:15
  • @Evan : Is that updating earlier ? Did you check types being sent in input & in DB match ? – whoami - fakeFaceTrueSoul Feb 27 '20 at 17:16
  • The original version was updating the first card in the array. So that led me to believe my array of ids was the right types. It's an array of strings, if that helps. – evan Feb 27 '20 at 17:20
  • And specifically, for my test, I'm using 4 ids: [ '5e45a85418385d873b412115', '5e45a86c18385d873b412119', '5e569fff9cb91a0017bc2dbe', '5e456f6c30fd19843048fc8b' ] – evan Feb 27 '20 at 17:22
  • @Evan : Are those `cards._id`'s strings in DB & also did you convert `userId` to `ObjectId()`? – whoami - fakeFaceTrueSoul Feb 27 '20 at 17:22
  • No, in the db they are MongoDB objectIds. – evan Feb 27 '20 at 17:23
  • I did not convert userId to ObjectId(). I haven't needed to in other queries, so I didn't think that was necessary. – evan Feb 27 '20 at 17:24
  • @Evan : not sure how it worked but in general you need to convert strings to `ObjectId()`'s & pass those in query. Check :: https://stackoverflow.com/questions/6578178/node-js-mongoose-js-string-to-objectid-function , unless types do match updates don't work.. – whoami - fakeFaceTrueSoul Feb 27 '20 at 17:25
  • Thanks, I made the change to the types, but it still doesn't appear to be making any of the updates. – evan Feb 27 '20 at 17:25
  • 1
    Added a callback for err as the last input and it worked. Thanks! – evan Feb 27 '20 at 17:35