error repeated many times when using findByIdAndUpdate

You don’t say what the error is but your code just updates the database based on currently held values in memory so if you had multiple clients that could cause chaos.
If it is single threaded or this is the ONLY place that updates those collections / fields then you may not need to worry about this.
Can you put pseudocode up on what it’s expected to do, along with example data that has caused the issue.

If dealing with money updates then it can be crucial to ensure that when you send an update to the database that you are updating data based on the latest information.
Either get the server to calculate the update or send the last known value as an extra match condition or have some form of checksum or timestamp for a document so you know that you’re updating data that’s in the same state on the server as you have in the database.
You can then check the update result to determine if the update completed and deal with it appropriately, in fact you should be doing that anyway ideally if ensuring that updates complete as expected is important to you. You need to avoid lost-updates if they are even a remote possibility.

You could also think about using transactions if it’s critical that multiple updates all either complete or do no complete.

You have no logging in the above, to try and diagnose the issue why not add logging to a collection to store how often each part is run and what the results are within loops and return results or at least their size.

1 Like