Mongoose.js交易 [英] Mongoose.js transactions

查看:77
本文介绍了Mongoose.js交易的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道MongoDB不像关系数据库那样支持事务,但是我仍然想知道如何为多个操作实现原子性.在网上搜寻时,我看到有人提到没有交易的交易.通读幻灯片,我仍然不清楚如何使用Mongoose.js来实现.

以以下代码段为例:

player.save(callback1);
story.save(callback2);

如何实现callback1和callback2以便它们一起成功或一起失败?

解决方案

如果您确实必须跨多个文档类型(在单独的集合中)进行事务处理,则可以使用一个存储要采取措施的表来实现此目的.

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

此插入是原子的,并且一次完成.然后,您可以执行操作"集合中的命令,并将其标记为已完成,或者在完成时将其删除,并在所有命令完成后调用原始回调.仅当您的操作处理循环是唯一更新数据库的内容时,此方法才有效.当然,您将不得不停止使用猫鼬,但是越早使用猫鼬越好.

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 mentioning Transactions without Transactions. Reading through the slides, I am still not clear how to implement that with Mongoose.js.

Take this code snippet for example:

player.save(callback1);
story.save(callback2);

How do I implement callback1 and callback2 so that they either succeed together or fail together?

解决方案

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.

这篇关于Mongoose.js交易的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆