Home > front end >  Deletion in FireStore (Latest Snip)
Deletion in FireStore (Latest Snip)

Time:01-05

I have a Data Table Like this i want to delete every document inside collection before invoke loadCheckOut. How can i dow that with latest JS Syntax. I am using React JS, and it initilize DB from getDb() method so methods like db.collection() not work on it i want a complete moduler solution

 const loadCheckout = async (priceId) => {
    //before adding we must delete existing collection
    const docRef_x = collection(db, `customers/${user.uid}/checkout_sessions`);
    const snapshot = await getDocs(docRef_x);
    const x = await deleteDoc(snapshot);

    const docRef = await addDoc(
      collection(db, `customers/${user.uid}/checkout_sessions`),
      {
        price: priceId,
        success_url: window.location.origin,
        cancel_url: window.location.origin,
      }
    );
    const ref = collection(db, `customers/${user.uid}/checkout_sessions`);
    const snap = onSnapshot(
      ref,
      { includeMetadataChanges: true },
      async (doc) => {
        var error = null,
          sessionId = null;
        var first = true;
        doc.forEach((ele) => {
          if (first) {
            error = ele.data().error;
            sessionId = ele.data().sessionId;
            first = false;
          }
        });
        console.log(sessionId);
        if (error) {
          alert(error);
        }
        if (sessionId) {
          const stripe = await loadStripe(stripe_public_key);
          stripe.redirectToCheckout({ sessionId });
        }
      }
    );
  };

CodePudding user response:

This won't work:

const snapshot = await getDocs(docRef_x);
const x = await deleteDoc(snapshot);

The deleteDoc function requires a single DocumentReference, while your snapshot is a QuerySnapshot. This has very little to do with the change in syntax, as snapshot.delete() also wouldn't have worked in v8 of the SDK and earlier.

To delete the documents in the query snapshot, loop over the results and delete them one by one:

snapshot.forEach((doc) => {
  deleteDoc(doc.ref);
});
  •  Tags:  
  • Related