具有Cloud功能的Firebase增量计数器 [英] Increment counter with 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:
错误每个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:
var chainCounterRef = db.collection('counters').doc('chains');
chainCounterRef.update({ count: FieldValue.increment(1) });
请参阅:
这篇关于具有Cloud功能的Firebase增量计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!