Home > Software design >  How do I check if a document exists within a collection (Firebase REACT)?
How do I check if a document exists within a collection (Firebase REACT)?

Time:11-14

For a project in class, we need to create accounts through the Google provider. Once signed in you get to create projects and such and they're saved to your account. The problem is once you log back in, my setDoc that I use for creating new users seams to overlap my getDoc function.. My teacher has also specified NOT to use get() or find() for some reason.. Thank you!

This is what I've tried and haven't gotten any good results from it:

const docRef = doc(db, 'membres', creds.user.uid);
//faire une condition si le id existe dans la base de donner
//si oui, getdoc
//sinon, setdoc

if (docRef.exists) {
  console.log('it exists!');
  await getDoc(docRef);
} else {
  console.log('No such document exists!');
  await setDoc(docRef, {
    nom: creds.user.displayName,
    email: creds.user.email,
    projets: [],
    contacts: []
  });
}

CodePudding user response:

The doc() function returns a DocumentReference and does not fetch the document or check if it exists. You'll have to use getDoc(docRef) to get the document at first place and then check if that exists.

Since you are not allowed to use getDoc(), you can add the document (use setDoc()) only when a user logs in for first time. Try:

const result = await signInWithPopup(auth, provider); 

const {isNewUser} = getAdditionalUserInfo(result) // <-- or result of signInWithRedirect();

if (isNewUser) {
  // user has signed in first time
  // setDoc(...)
} else {
  // Existing user, document created already. 
}
  • Related