Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a firestore document when a new user is created with firebase auth using node.js

I'm using firebase cloud functions, firebase auth and firestore. I've done this before with firebase database but just not sure with firestore how to set a document in the users collection to the uid of a newly created firebase auth user.

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

const db = admin.firestore()

exports.createUser  = functions.auth.user().onCreate(event => {

 const uid  = event.data.uid;
 console.log(uid);

 db.collection('users').doc(uid);


});

The above completes ok in the logs but the uid isn't getting set in the database. Do I need to call set at some stage?

like image 793
Mike Avatar asked Dec 10 '22 09:12

Mike


2 Answers

const collection = db.collection("users")
const userID = "12345" // ID after created the user.
collection.doc(userID).set({
    name : "userFoo", // some another information for user you could save it here.
    uid : userID     // you could save the ID as field in document.
}).then(() => {
    console.log("done")
})
like image 82
aboodrak Avatar answered Jan 05 '23 00:01

aboodrak


Note, that the onCreate return has changed, it does return the user now, so event.data.uid isn't valid anymore.

The full function should look something like this, it will create a document with the user's uid in the "users" root-collection.

exports.createUser = functions.auth.user().onCreate((user) => {
    const { uid } = user;

    const userCollection = db.collection('users');

    userCollection.doc(uid).set({
        someData: 123,
        someMoreData: [1, 2, 3],
    });
});
like image 24
ffritz Avatar answered Jan 05 '23 00:01

ffritz