I have this Cloud Function:
exports.addUser = functions.auth.user().onCreate(async (user) => {
const {uid, email} = user;
const userRecord = {
createdAt: admin.firestore.FieldValue.serverTimestamp(),
...(email && {email}),
};
try {
await db.collection("users").doc(uid).set(userRecord);
return true;
} catch (error) {
console.error("Error adding user:", error);
return null;
}
});
Which works fine when I sign in anonymously. If I try to link the newly created anonymous account with email and password in client-side code using:
val credential = EmailAuthProvider.getCredential(email, password)
currentUser?.linkWithCredential(credential)?.await()
This function gets somehow triggered and it overwrites the user document in Firestore, even if it's an upgrade and not an account creation. Is this correct behavior? How to avoid this?
This answer:
Says the opposite.
If the triggering behavior of the function can't be changed by code or configuration (which is likely), then your only real solution here is to change your code to use a transaction to first check for the existence of the user document, and only create it if it doesn't already exist. You could also update the document instead in the transaction if you want to record something new in it instead.