Grrrrrag
Grrrrrag

Reputation: 47

Write a user to Firestore after new user registration

this is my function:

 const functions = require('firebase-functions');
 exports.newUserToFirestore = functions.auth.user().onCreate((user) => {
    var current = new Date().toString();
    var email = user.email;
    var nameIndex = email.indexOf('@');
    var nameUser = email.substring(0,nameIndex);
    console.log(user.uid + ',' + nameIndex + ',' + nameUser)
    firebase.firestore().collection('users').doc()
    .set({
        userId: user.uid,
        email: user.email,
        name: nameUser,
        creationDate: current
        })
  });

Deploy worked, but when I create a new User, i get Function execution took 9 ms, finished with status: 'error' in the Firebase functions Logs. What am I doing wrong?

Upvotes: 0

Views: 916

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83093

In Cloud Functions, if you want to interact with the other Firebase services, you need to use the Admin SDK. As explained in the doc, you need to load the firebase-admin module, and initialize an admin app instance.

In your case, it seems that you don't use the firebase-admin module and don't initialize an admin app instance.

In addition, as @SomeoneSpecial commented, in order to correctly manage the CF life cycle you need to return a promise when all the asynchronous work is completed (more detail here). Since the set() method returns a Promise, just return it.

So you need to modify your code as follows:

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

 exports.newUserToFirestore = functions.auth.user().onCreate((user) => {
    var current = new Date().toString();
    var email = user.email;
    var nameIndex = email.indexOf('@');
    var nameUser = email.substring(0,nameIndex);
    console.log(user.uid + ',' + nameIndex + ',' + nameUser)

    return admin.firestore().collection('users').doc()  // <= See that we use admin here
    .set({
        userId: user.uid,
        email: user.email,
        name: nameUser,
        creationDate: current
        })
  });

Note that a common practice when creating a user document in Firestore is to use the user ID as the Firestore document ID. This way it is easier to query this doc from the front-end.

Upvotes: 4

Related Questions