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?
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")
})
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],
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With