Mike
Mike

Reputation: 1331

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?

Upvotes: 4

Views: 10298

Answers (2)

ffritz
ffritz

Reputation: 2261

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],
    });
});

Upvotes: 6

aboodrak
aboodrak

Reputation: 873

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")
})

Upvotes: 8

Related Questions