简体   繁体   中英

Firebase: Trigger event in Firestore on new user created in FirebaseAuth

I wrote a very simple Cloud Function to add some fields in Firestore with some info from the newly created FirebaseUser in FirebaseAuth.

In Firestore, I have a collection named "highscore". Everytime, a new user is created, I want to add a document with the firebaseusers uid as document, and 2 fields, like:

highscore/uid/score & highscore/uid/usernick (eg highscore/fgt38gudg9/430 & highscore/fgt38gudg9/cooldude45)

This is my function:

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp();

const db = admin.database()

//On user creation, trigger: Add information to /highscore/uid
exports.onUserCreation = functions.auth.user().onCreate((user) => {

    const collection = db.collection("highscore")
    const userid = user.uid
    const usernick = user.displayName
    collection.doc(userid).set({
        score: 0
        user: usernick
    })

})

However, when the function is triggered, I run into this error:

TypeError: db.collection is not a function
    at exports.onUserCreation.functions.auth.user.onCreate (/srv/index.js:11:24)
    at cloudFunctionNewSignature (/srv/node_modules/firebase-functions/lib/cloud-functions.js:120:23)
    at /worker/worker.js:825:24
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:229:7)

I can't figure this out. Any suggestions?

我认为您正在使用Firstore:

const db = admin.firestore()

admin.database() gets you a reference to the Realtime Database instance for your project. What you want to use instead is admin.firestore() .

Also, you will want to return the promise that you get from set() , otherwise, the operation might not complete before the function terminates.

return collection.doc(userid).set({
    score: 0
    user: usernick
})

Be sure to read the documentation about terminating functions to understand your obligations in dealing with async work represented by promises.

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