-1

I am using Google Cloud Function, but since it runs on a older version of Node, I can not use this answer anymore. I want a function that will batch delete all the documents in a collection and returns the data from it. This is my attempt:

function deleteCollectionAndReturnResults(db, collectionRef, batchSize) {
  var query = collectionRef.limit(batchSize);
  return deleteQueryBatch(db, query, batchSize, []);
}

function deleteQueryBatch(db, query, batchSize, results) {
  return query.get().then(snapshot => {
    if (snapshot.size == 0) return 0;
    var batch = db.batch();
    snapshot.docs.forEach(doc => { 
      if (doc.exists) {results.push(doc);}
      batch.delete(doc.ref); 
    });
    return batch.commit().then(() => snapshot.size);
  }).then(function(numDeleted) {
    if (numDeleted >= batchSize) {
      return deleteQueryBatch(db, query, batchSize, results);
    }else{
      return results
    }
  });
}

But when I run it like this:

exports.tester = functions.firestore.document('x/{x}').onCreate(event => {
      deleteCollectionAndReturnResults(db, db.collection("x"), 100).then(docs => {
        console.log(docs)
      })
})

This is my output:

enter image description here

Is there something wrong why I do get the 'function returned undefined'?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
J. Doe
  • 12,159
  • 9
  • 60
  • 114

1 Answers1

1

Your tester function doesn't return anything. Instead, it should return a promise that's resolved when all the work is complete. It looks like you've simply forgotten to return the promise returned by deleteCollectionAndReturnResults:

exports.tester = functions.firestore.document('x/{x}').onCreate(event => {
    return deleteCollectionAndReturnResults(db, db.collection("x"), 100).then(docs => {
        console.log(docs)
    })
})
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441