Mongoose.js transactions

前端 未结 6 1011
栀梦
栀梦 2021-01-30 18:14

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

6条回答
  •  抹茶落季
    2021-01-30 18:40

    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.

提交回复
热议问题