skip to Main Content

How to throw an error if firestore document does not exist?

const cancel = (id) => {
  if(window.confirm("Are you sure to cancel this appointment ?")) {
    const userDoc = doc(db, 'accounts', id)
    deleteDoc(userDoc)
  }
}

2

Answers


  1. you can use the condition if(!userDoc.exist) return ;ยท

    it doesn’t work for because you need to use it this way

    const cancel = (id) => {
      if(window.confirm("Are you sure to cancel this appointment ?")) {
        const userRef = doc(db, 'accounts', id)
        const userDoc = await userRef.get();
       if(!userDoc.exist) return console.log("throw an error");
        deleteDoc(userRef)
      }
    }ยท
    
    Login or Signup to reply.
  2. Your userDoc variable is a reference to a document, it doesn’t yet have any data of that document from the database.

    If you want to check whether the document exists, you’ll first have to get it from the database. From that link comes this code sample, which is quite close to what you’re trying to do:

    import { doc, getDoc } from "firebase/firestore";
    
    const docRef = doc(db, "cities", "SF"); // ๐Ÿ‘ˆ Create reference
    const docSnap = await getDoc(docRef);   // ๐Ÿ‘ˆ Load document data
    
    if (docSnap.exists()) {                 // ๐Ÿ‘ˆ Check if it exists
      console.log("Document data:", docSnap.data());
    } else {
      // doc.data() will be undefined in this case
      console.log("No such document!");
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search