Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Atomic multiple operations in Mongoose

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?

like image 610
k88074 Avatar asked Dec 02 '14 20:12

k88074


1 Answers

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.

like image 119
k88074 Avatar answered Sep 21 '22 10:09

k88074