skip to Main Content

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


  1. 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:

    const userDocRef = doc(db, "users", userCredentials.user.uid);
    const userDocSnapshot = await getDoc(userDocRef);
    
    if (userDocSnapshot.exists()) {
      // Document exists, so the user was already registered
      await updateDoc(userDocRef, {
        // fields to update
      });
    } else {
      // Document does not exist, so the user is signing up for the first time
      await setDoc(userDocRef, {
        uid: userCredentials.user.uid,
        email: userCredentials.user.email,
        // other fields
      });
    }
    

    Let me know if something is unclear or bad commented and everyone feel free to edit.

    Login or Signup to reply.
  2. 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 type FirebaseError: No document to update and you would then use the setDoc() method in a catch() 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).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search