[SOLVED] How to set/replace data in document's array field by key-value

screenshot of my dictionary: corrections at the right side are waiting for admin approve or reject.

My Article schema contains array field, witch contains objects:

{ 
words: [objects], 
translations: [objects], 
editedAt: someDate, 
editedBy: userId0, 
lastEvent: "added article",
corrections: [
  {
    words: [objects], 
    translations: [objects], 
    editedAt: someDate, 
    editedBy: userId1, 
  }, 
  {
    words: [objects], 
    translations: [objects], 
    editedAt: someDate, 
    editedBy: userId2, 
  }
]
}

I need to update at the same time lastEvent and one object from corrections, where editedBy == myUserId.
The Idea is not to store more than one correction per user for an Article.
I tried out many things from this forum and mongo docs and stackoverflow etc, but didn’t reach what I wanted.

Worked fine this code, but unfortunately it fires 3 times hook-update , (which I use for other purposes):

        Articles.update(
            {_id: doc._id},
            { $set: { lastEvent : {type: "edit request" },},
         },);

        Articles.update(
            {_id: doc._id },
            { $pull: { corrections : { editedBy: userId } } },
            );
        
        Articles.update(
            {_id: doc._id},
            { $push: { corrections : correction } },
            );
    }

Please, if somebody knows how to reach this by one update({}), share the solution…

Have you tried simply updating the entire document?

  1. find the document.
  2. make the changes to the document in your code
  3. update the entire document.

If this is on the client it is pretty cheap.

If you really need to do a couple of operations on a large document within MongoDB you should read up on the aggregation pipeline. Again, I do not recommend this route for you, simply update the entire document.

1 Like

Yes , i have done it) I sucked with mongodb $push, $pull, etc… and forget about old good js))
I just get the document article.corrections field, changed it , and send it in ordinary {$set} modifier )
sometimes simple solution looks difficult, because you seek it in not good way…
Thank you again :wink:

1 Like