使用 Cloud Functions for Firebase 递增计数器 [英] Increment counter with Cloud Functions for Firebase

查看:22
本文介绍了使用 Cloud Functions for Firebase 递增计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have seen an increment counter with Cloud Functions referencing Realtime Database, but not Firebase Firestore yet.

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

I have a cloud function that listens for new documents:

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;
});

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

I'm attempting the above transaction, but when I run firebase deploy in terminal I get this error:

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

error Each then() should return a value or throw promise/always-return functions predeploy error: Command terminated with non-zero exit code1

这是我第一次尝试任何 node.js,我不确定我是否写对了.

This is my first attempt at anything node.js, and I'm not sure I've written this right.

推荐答案

现在有一种更简单的方法来增加/减少文档中的字段:FieldValue.increment().您的样本将是这样的:

There is now a much simpler way to increment/decrement a field in a document: FieldValue.increment(). Your sample would be something like this:

const FieldValue = require('firebase-admin').firestore.FieldValue;
var chainCounterRef = db.collection('counters').doc('chains');
chainCounterRef.update({ count: FieldValue.increment(1) });

见:

这篇关于使用 Cloud Functions for Firebase 递增计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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