[英]Increment Realtime Database count on new user with Firebase Cloud Function
* UPDATED: THIS WORKS. * 更新:这有效。 SEE ANSWER BELOW *见下面的答案*
I'm trying to write a Firebase Cloud Function that increments a Realtime Database /userCount
value whenever a new user is created.我正在尝试编写一个 Firebase 云函数,它会在创建新用户时增加实时数据库/userCount
值。
I've tried the following, but am getting "TypeError: userCountRef.transaction is not a function" in incrementCountOnNewUser
.我尝试了以下操作,但在incrementCountOnNewUser
收到“TypeError: userCountRef.transaction is not a function”。
Transactions are working for my other function incrementCountOnOpen
when the value of garage
is set to true
, but the ref
is derived from the after
event object.当garage
的值设置为true
,事务正在为我的另一个函数incrementCountOnOpen
工作,但ref
是从after
事件对象派生的。
Any suggestions on how to do this?关于如何做到这一点的任何建议?
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
// const userCountRef = functions.database.ref("/userCount"); // does NOT work
const userCountRef = admin.database().ref('/userCount'); // THIS WORKS!
exports.incrementCountOnNewUser = functions.auth.user().onCreate((user) => {
return userCountRef.transaction(count => count + 1);
});
exports.incrementCountOnOpen = functions.database.ref("/garage").onUpdate(({after}) => {
const countRef = after.ref.parent.child('count');
const newValue = after.val();
return newValue
? countRef.transaction(count => count + 1)
: null;
});
It turns out that the code above works!事实证明上面的代码有效! I had switched from the commented out code (which does NOT work).我已经从注释掉的代码(这不起作用)切换了。 I guess it didn't wait long enough for it propagate after I published, because I see it working now!我想它在我发布后没有等待足够长的时间来传播,因为我现在看到它正在运行!
Sorry for the confusion.对困惑感到抱歉。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.