简体   繁体   中英

I am trying to delete some data from firestore but there is a problem (react)

export function DeletePayment(paymentRefs) {
  return async (dispatch) => {
    await firebase
    .firestore()
    .collection("payments")
    .doc(firebase.auth().currentUser.uid)
    .collection("payment")
    .where("uid", "==", firebase.auth().currentUser.uid)
    .onSnapshot(async (result) => {
      const batch = firebase.firestore().batch();
      paymentRefs.forEach((ref) => {
        batch.delete(ref);
      });
      await batch.commit();
    })
  }
}

paymentRefs is an object of arrays now when running this code i get this error

Unhandled Rejection (FirebaseError): Expected type 't', but it was: a custom Object object

Try this instead:

 export function DeletePayments(paymentRefs) { const batch = firebase.firestore().batch(); paymentRefs.forEach((ref) => { batch.delete(ref); }); return batch.commit() }

This will delete all document references at the end of the batch and will return a promise that you can handle every time the function is called.

EDIT: If you have the id of the payment inside the every object in paymentRefs , you could try something like this.

 export function DeletePayments(paymentRefs) { const batch = firebase.firestore().batch(); paymentRefs.forEach((ref) => { batch.delete(firebase.firestore().doc(`payments/${firebase.auth().currentUser.uid}/payment/${ref.id}`)); }); return batch.commit() }

Find an example for how to clean some notification collection in case its useful...

async function checkForNotifClean(docsToKeep:firebase.firestore.QuerySnapshot<firebase.firestore.DocumentData>) {
  const db = firebase.firestore();
  const notifCollection = db.collection('notifications')
  const allData = await notifCollection.get();
  allData.docs.forEach(doc => {
    const filtered = docsToKeep.docs.filter(entry => entry.id === doc.id); 
    const needsErase = filtered.length === 0;
    if (needsErase) {
      const id = doc.id; 
      notifCollection.doc(id).delete();
    }
  })
}
export function DeletePayment(paymentRefs) {
  return async (dispatch) => {
    const batch = firebase.firestore().collection("payments").doc(firebase.auth().currentUser.uid).collection("payment");
    paymentRefs.forEach(async (ref) => {
      await batch.doc(ref).delete();
    });
    dispatch({
      type: 'ENQUEUE_SNACKBAR', notification: {
        message: 'Payment has been Deleted',
        key: new Date().getTime() + Math.random(),
        options: {
          variant: 'success',
        }
      }
    })
  }
}

that how I did it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM