Mongoose.js transactions

前端 未结 6 1116
栀梦
栀梦 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:26

    If you really must have transactions across multiple documents types (in separate collections) the means to achieve this is with a single table that stores actions to take.

    db.actions.insert(
    { actions: [{collection: 'players', _id: 'p1', update: {$set : {name : 'bob'} } },
                {collection: 'stories', _id: 's1', update: {$set : {location: 'library'} } }], completed: false }, callback);
    

    This insert is atomic, and all done at once. You then can perform the commands in the 'actions' collection and mark them as complete or delete them as you complete them, calling your original callback when they are all completed. This only works if your actions processing loop is the only thing updating the db. Of course you'll have to stop using mongoose, but the sooner you do that the better you'll be anyway.

提交回复
热议问题