I know MongoDB doesn\'t support transactions as relational databases do, but I still wonder how to achieve atomicity for several operations. Hunting around the web, I see people
You can simulate a transaction by manually rolling-back the changes whenever an error occurs. In your above example, simply remove the saved document if the other one fails.
You can do this easily using Async
:
function rollback (doc, cb) {
doc.remove(cb);
}
async.parallel([
player.save.bind(player),
story.save.bind(story),
],
function (err, results) {
if (err) {
async.each(results, rollback, function () {
console.log('Rollback done.');
});
} else {
console.log('Done.');
}
});
Obviously, the rollback itself could fail -- if this is a not acceptable, you probably need to restructure your data or choose a different database.
Note: I discussed this in detail on this post.