I have a scenario where an API call needs to update two separate collections. If one update fails I need to revert back the first update. How do I ensure that either both the operations complete successfully or none. To help clarify, here's the situation. Using MongoJS in express framework.
Question Model
{
_id: ObjectId(),
title: String,
description: String,
accepted: String,
// Some other fields
}
Answer Model
{
_id: ObjectId(),
qid: String, //ObjectId of question its linked to
body: String,
accepted: boolean,
// Some other fields
}
Approach 1:
First pull the answer corresponding to the id
sent in request. Mark it as accepted and get the qid
. Insert the answer id
in the question document corresponding to qid
. If second operation fails, revert back first operation. But if db connection is lost, it cannot be performed.
Approach 2
First get the question corresponding to qid
. Update the accepted
field with answer id
and then get the answer corresponding to it and mark it as accepted.
Then there is the case that if one answer is accepted, we need to make all other answers as not accepted. that's a third operation. Furthermore, its a toggle operation, so if it was already accepted, we need to do the reverse.
I have a feeling there's a cleaner and safer way to handle this situation.