[SERVER-50011] Can a transaction used again after document save fails using that transaction? Created: 29/Jul/20  Updated: 27/Oct/23  Resolved: 31/Jul/20

Status: Closed
Project: Core Server
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Question Priority: Minor - P4
Reporter: Sajith Neyomal Assignee: Jonathan Streets (Inactive)
Resolution: Works as Designed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Attachments: Text File function.txt    
Participants:

 Description   

Let's imagine a situation like this.

I need to generate 10 documents in the same collection. So I use a loop. The loop won't stop until 10 documents are saved. Even if a single iteration fails, loop continues until the total number of saved documents are 10. This works fine. Then I added transactions to scenario. Let's say transaction starts before the loop executes inside a try catch block. If any error occurs transaction fails except errors in the loop. Because they are ignore to complete the loop until 10 documents are saved. So the problem occurs when transaction is applied to a document when saving. If the loop runs without errors there won't be any problem. But I purposely add a duplicate record on iteration 5 by using a counter. 

What I expected was to complete the loop and commit the transaction ignoring the duplicate record as the loop however completes with 10 saved documents.

But when a manual error is introduced using a duplicate record from iteration 6 a MongoDB error is thrown. 'MongoError: Transaction 1 has been aborted.\n' So the loops runs infinite until I add a error counter and throw error out of the loop when error counter reaches a given count.

So what is wrong in this situation. My guess is, as the document save fails in the iteration 5 due to the duplicate record, the transaction aborts at that point. So the transaction is not available for the iteration 6 as it is already aborted. I don't know weather this is the default behavior of MongoDB. Please verify and is there any way to go around this?

I'm using NodeJS and Mongoose. Function is attached as a text file. Thank you!

 



 Comments   
Comment by Jonathan Streets (Inactive) [ 31/Jul/20 ]

hi sajithneyo94@gmail.com,
the transaction is working as expected, on the docs it says that transaction sessions are an "all-or-nothing" type operation. Once the insert fails, then the other inserts are rolled back and the transaction session is ended. If operations are expected to fail, or if the set of operations do not need to be atomic, then I think your original design is best, which has loops but no transaction session.
regards
Jon

Generated at Thu Feb 08 05:21:28 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.