Reputation: 399
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);
});
}
});
});
Upvotes: 2
Views: 681
Reputation: 13
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.
Upvotes: 0
Reputation: 1084
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
Upvotes: 0
Reputation: 1872
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
Upvotes: 1