首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何为firebase管理员实时数据库编写批处理事务?

如何为firebase管理员实时数据库编写批处理事务?
EN

Stack Overflow用户
提问于 2020-02-08 11:43:52
回答 1查看 516关注 0票数 0

有没有办法用admin sdk对实时数据库中的不同字段进行批量事务处理?目前,我使用的是:

代码语言:javascript
复制
exports.function = functions.https.onCall((data, context) => {

    var transactions = new Object();

    transactions[0] = admin.database().ref('ref1/')
        .transaction(currentCount => {
            return (currentCount || 0) + 1;
        }, (error, committed, dataSnapshot) => {...})

    transactions[1] = admin.database().ref('ref2/')
        .transaction(currentCount => {
            return (currentCount || 0) + 1;
        }, (error, committed, dataSnapshot) => {...})

    return admin.database().ref().update(transactions)
                             //  |^|  error occurs right above '|^|', but i don't know why, i suspect it may have something to do with transactions object, and if so, what's the proper way to do batched transactions?
        .then(result => {...})
        .catch(error => {
            console.error('error: ' + error)
        })
}

但每次调用此函数时,尽管事务确实作为批处理工作,但仍会抛出以下错误:

代码语言:javascript
复制
Unhandled error TypeError: obj.hasOwnProperty is not a function
    at each (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:541:17)
    at validateFirebaseData (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:1470:9)
    at /srv/node_modules/@firebase/database/dist/index.node.cjs.js:1487:13
    at each (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:542:13)
    at validateFirebaseData (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:1470:9)
    at /srv/node_modules/@firebase/database/dist/index.node.cjs.js:1559:9
    at each (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:542:13)
    at validateFirebaseMergeDataArg (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:1557:5)
    at Reference.update (/srv/node_modules/@firebase/database/dist/index.node.cjs.js:13695:9)
    at admin.firestore.collection.doc.collection.doc.create.then.writeResult (/srv/index.js:447:43)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-08 13:51:51

您不能将一堆事务传递到update()调用中,这就是错误消息(诚然有点令人困惑)试图告诉您的。

Firebase没有嵌套或批处理事务的概念。如果您需要跨多个位置执行事务,则需要在所有这些位置之上的节点上将其作为单个transaction调用运行。正如您可能猜到的那样,这种多位置事务上的争用很快就会成为吞吐量限制,因此您需要考虑替代解决方案。

对于您的用例,我能想到的“最简单”的方法是用单个多位置更新替换这两个事务,然后使用服务器端安全规则来验证操作。

有关如何执行类似操作的示例,请参阅我的答案:Is the way the Firebase database quickstart handles counts secure?

使用这种方法可以防止大部分争用,因为多位置更新不需要读取-发送-检查整个顶级节点,而只需要更新的低级节点。

您可能必须修改您的数据结构,甚至可能写入额外的数据,才能实现这种方法。但作为回报,您将获得可伸缩性更强的事务性更新。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60123745

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档