Imagine this db structure:
/users(collection)
userId/ (doc)
likes/ (collection)
postId1 (doc)
postId2 (doc)
I am implementing a function for liking/disliking posts.
For that, I am running a transaction where I get
the like status (isLiked) using the transaction, in order to do this (like) or that (dislike).
When a like operation is performed, I need to add the liked post to the likes
sub-collection of the user that gave the like.
But... what if the document of the user (that is liking the post) is deleted (in the UI I have a section for user profile deletions) during the like operation?
If I just do:
transaction.create(`users/${userId}/likes/${postId}`, denormalizedPostData);
will the removal of the user doc be detected by the transaction?
If not, what if I also delete the likes/ subcollection of the user when deleting its doc?
deleteUserDoc(userDocRef);
deleteFullCollection(userLikesRef, batchSize);
Will the
transaction.create(`users/${userId}/likes/${postId}`, data);
detect the "change" (the deletion of the doc) and re-execute the transaction?
I am asking this because I know that we need to make sure that reads are situated before writes in the body of transactions, in order to re-execute the transaction if the read docs change... but, what about this situation?
I am afraid of re-creating the user doc because of just attaching a doc to the user likes collection using the transaction.create()
operation.
Should I make an extra read in the top of the transaction?
transaction.get(userRef); // Just to ensure the re-execution
CodePudding user response:
If you read the document the transaction handler and then write modification to it in that same handler, then the Firestore SDK sends the pre-transaction state and post-transaction state of that document to the server. This allows the server to then detect whether the document was modified during the transaction, including whether it was deleted.