Firebase云端函数:增量计数器

使用事务处理实时数据库触发器增加计数器是否可以接受?

exports.incPostCount = functions.database.ref('/threadsMeta/{threadId}/posts') .onWrite(event => { admin.database().ref('/analytics/postCount') .transaction(count => { if (count === null) { return count = 1 } else { return count + 1 } }) }); 

非也! 事实上,这就是这个代码示例中的工作方式 ,虽然有一些小的区别:

 exports.countlikechange = functions.database.ref("/posts/{postid}/likes/{likeid}").onWrite((event) => { var collectionRef = event.data.ref.parent; var countRef = collectionRef.parent.child('likes_count'); return countRef.transaction(function(current) { if (event.data.exists() && !event.data.previous.exists()) { return (current || 0) + 1; } else if (!event.data.exists() && event.data.previous.exists()) { return (current || 0) - 1; } }); }); 

值得注意的是,这个示例根据是否正在创build或删除子节点来处理递增和递减大小写。