使用事务使用实时数据库触发器递增计数器是否可以接受?
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
}
})
});
答案 0 :(得分:37)
当然!事实上,这正是它的完成方式in this code sample,尽管存在一些小差异:
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;
}
});
});
值得注意的是,此示例处理增量和减量情况,具体取决于是创建还是删除子节点。