With latest version of Firebase Javascript SDK (10.1.0) I am using signInWithPopup
to authenticate users through Providers and then saving their credentials inside the DB:
userCredentials = await signInWithPopup(auth, new GoogleAuthProvider());
await setDoc(
doc(db, "users", userCredentials.user.uid),
{
uid: userCredentials.user.uid,
email: userCredentials.user.email,
...,
},
{ merge: true },
);
How can I know if the recently set document was created (user was authenticated for the first time, i.e. signed up to the service) or updated (user was already registered)?
PS: I would like to avoid querying the DB to check for existing email, as I would need to change the access rules and make all users data available to anyone.
2
Answers
I normally used getDoc for such use cases. I call it before setDoc. Based on your example code I would adapt my code like this:
Let me know if something is unclear or bad commented and everyone feel free to edit.
The only way to know if a Firestore document is present in the database is to query it.
As a workaround you could use the
updateDoc()
method to write to the DB and in case the doc does not already exist it will return an error of typeFirebaseError: No document to update
and you would then use thesetDoc()
method in acatch()
block to create it.BUT note that this approach costs a write each time the doc does not exist. It’s up to you to do the math to calculate the best option for you (pay for a read each time you want to know if the doc exists or pay for an extra write when you actually create the doc).