Consider a schema:
var userSchema = mongoose.Schema({
...
followers: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
following: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }]
...
}
When userA
follows userB
, userB
is to be pushed in userA.following
and userA
is to be pushed in userB.followers
. Both operations require a .save()
.
What is a good way - perhaps conceptual - of ensuring that if either one of the .save()
fails, both documents are left untouched?
I turned out doing as @BatScream suggested in the first comment. I reorganized the Schemas of my data and removed the list followers
.
After reading quite a lot on the topic my humble conclusion is that doing transactions across multiple documents in mongoDB/Mongoose.js is, though doable, probably not the smartest-safest thing to do. When implementing two-phase commits rollback actions can themselves fail.
If atomic operations across multiple documents are necessary probably MongoDB is not the right tool. However, a bit of data restructuring/reorganization can perhaps some times make multidocument transactions unnecessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With