具有Cloud功能的Firebase增量计数器

Aus*_*nyi 3 node.js firebase google-cloud-functions google-cloud-firestore

我已经看到了使用Cloud Functions引用实时数据库的增量计数器,但是还没有Firebase Firestore。

我有一个监听新文档的云功能:

exports.addToChainCount = functions.firestore
    .document('chains/{name}')
    .onCreate((snap, context) => {

    // Initialize document
    var chainCounterRef = db.collection('counters').doc('chains');

    var transaction = db.runTransaction(t => {
        return t.get(chainCounterRef).then(doc => {
            // Add to the chain count
            var newCount = doc.data().count + 1;
            t.update(chainCounterRef, { count: newCount });
        });
    }).then(result => {
        console.log('Transaction success!');
    }).catch(err => {
        console.log('Transaction failure:', err);
    });
    return true;
});
Run Code Online (Sandbox Code Playgroud)

我正在尝试上述交易,但是firebase deploy在终端中运行时出现此错误:

错误每个then()应该返回一个值或抛出promise / always-return函数预部署错误:命令以非零退出代码终止

这是我对任何node.js的首次尝试,而且我不确定我是否写的正确。

Fra*_*len 16

现在有一种更简单的方法来增加/减少文档中的字段:FieldValue.increment()。您的示例将如下所示:

var chainCounterRef = db.collection('counters').doc('chains');
chainCounterRef.update({ count: FieldValue.increment(1) });
Run Code Online (Sandbox Code Playgroud)

看到:

  • 还有另一个伟大且最简单的解决方案,@FrankvanPuffelen。必须添加 `const FieldValue = require('firebase-admin').firestore.FieldValue;` 才能使其工作。 (8认同)