Bright
Bright

Reputation: 1067

Deleting documents in firestore with cloud functions

i am trying to delete a group of documents from a query using cloud functions. The cloud function is called and exits with status ok but the documents are not deleted. What could be the issue.

exports.deleteExpiredSellerPosts = functions.firestore
    .document('sellerPost/{post}')
    .onCreate(async(snapshot,context)=>{
    const now=snapshot.updateTime
    const post=snapshot.data();
    const seller=post.seller;
    const postsToDelete = await admin.firestore()
        .collection('sellerPost')
        .where("seller", "==" ,seller)
         .orderBy('expireTime','desc')
         .endAt([now])
    postsToDelete.get().then(function(querySnap){
       querySnap.forEach(function(doc){
           console.log(doc);
         doc.ref.delete();
       })
   })
   console.log('Success');
   return 0;
 })

I receive no error on console but documents are not deleted.

Upvotes: 0

Views: 662

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317372

If you follow the documentation, you will find that you are obliged to return a promise that resolves only after all the async work is done for the function. Otherwise, Cloud Functions will shut things down that are not complete at the time the function returns.

You've got a few problems here. Firstly, you're using await with something that doesn't return a promise, which means it's not doing anything at all. Secondly, your use of then on the the promise returned by get() is not pausing the execution of the code to wait for the query to finish. Thirdly, you're completely ignoring the promises returned by each call to delete(). You will have to rewrite this to handle all the promises correctly.

Minimally, you should consider:

  • Using await on the call to get() pause the function and wait for the query to complete
  • Use a for loop (not forEach) to iterate the document resu;ts, and use await on each call to delete() to wait for each document to be deleted.

Upvotes: 1

Related Questions