0

Working in NodeJS with Mongoose, though the methods are all the same.

So I have documents like (simplified):

{_id: 1, message: 'text1'}
{_id: 2, message: 'text2', reactions: [{_id: autoGen1, user: 'bob', reaction:''},
                                       {_id: autoGen2, user: 'bob', reaction:''}
                                       {_id: autoGen3, user: 'meg', reaction:''}]}

I want to run an update query that finds a message and either

  1. Adds the reaction if it doesn't exist
  2. Removes the reaction if it does exist

The user + reaction make a "unique, compound key".

edit

Much testing and experimentation later, I clearly misunderstood how $cond operated and its use-case. Evaluating other options. Open to suggestions.

edit2 Removed my previous, bad attempts. Post was getting too long.

Current Solution: https://mongoplayground.net/p/cgk6qgZ6l9k
Solution based on link in the comments; modified due to array contents.

I really don't like this solution. It's long. It's ugly. Adding an element probably doesn't add the _id. Not an elegant solution overall, in my opinion, unlike the tidy versions linked on SO that deal with primitive arrays and not arrays of objects.

I tried using $elemMatch and $in without success in that playground.

SimpleMind
  • 29
  • 7
  • Here is a SO post with similar issue and an answer: [How to toggle an element in array in MongoDB](https://stackoverflow.com/questions/51618537/how-to-toggle-an-element-in-array-in-mongodb/62380969#62380969). – prasad_ Jun 18 '21 at 06:33
  • Awesome, thank you!!!! I swear I've been searching SO for hours haha. – SimpleMind Jun 18 '21 at 07:20
  • Oof. Still struggling with this. So close. So close. So, since my array isnt an array of primitives, but an array of objects, I have to match the exact object with $in, $setDifference, $concatArrays. For example, { $in: [ {user: username, reaction: reaction}, "$reactions" ] }. The problem is that since its an object, MongoDB auto-generates an id field and I have to match that too =/ – SimpleMind Jun 18 '21 at 12:05
  • Edited post with current solution ( https://mongoplayground.net/p/cgk6qgZ6l9k ). I tried using $in without success due to the _id fields. Also tried using $elemMatch but I couldnt get a version with $elemMatch to compile/run. – SimpleMind Jun 18 '21 at 13:05

0 Answers0