简体   繁体   中英

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.

I've tried the following, but am getting "TypeError: userCountRef.transaction is not a function" in incrementCountOnNewUser .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM