简体   繁体   中英

Cloud Firestore delete function

All,

I am using Firestore as a backend and am trying to write a cloud function that will run on the first of every month. This function will need to delete every database entry that falls before the date the function is running. I was able to get the following function worked out but it will not delete any entries. Maybe someone can help me get it worked out.

export const deleteOldPrayerRequests = functions.pubsub.schedule('0 0 1 * *').onRun(async (context) => {
    const date = new Date();
    console.log('---> Timestamp', context.timestamp);
    console.log('---> Date Today', date);
    console.log('---> Date Today', date.setDate(date.getDate()));
    console.log('---> Date 14 days ago', date.setDate(date.getDate() - 14));
    const snapshot = await admin.firestore().collection('prayerRequests').get();
    snapshot.docs.forEach(doc => {
        const ts = doc.get('dateSubmitted');
        if (date.setDate(date.getDate() - 14) >= ts.toMillis()) {
            console.log(doc.data());
            doc.ref.delete().then((data: any) => {
                console.log(data);
            }).catch((error: any) => {
                console.log(error);
            });
        }
    });
});

This is the sample code snippet provided on Firestore official documentation for delete documents.

db.collection("cities").doc("DC").delete().then(function() {
  console.log("Document successfully deleted!");
}).catch(function(error) {
  console.error("Error removing document: ", error);
});

Reference Read More

You need to return a promise that resolves when all the async work is complete, or Cloud Function will terminate it all early. – Doug Stevenson

I have had a similar issue. In order for the delete to work, a callback function needs to be used. The way to handle it seems to keep changing as Angular gets updated. This is my solution using Angular 8 (latest everything):

    this.db.collection('prayerRequests')
    .get()
    .subscribe((snapshot) =>{
      snapshot.forEach(doc => {
          this.db.collection('dateSubmitted').doc(doc.id).delete()
      });
    })

Hope this works out for you.

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