sebagl
sebagl

Reputation: 15

Deleting document from Firestore with Cloud Functions

I am trying to make this Cloud Function to work. I would like to delete a document from Firestore that has as name the previous date of function execution. This function is supposed to be executed every night at 2am, but for some reason it is not working. Here is my code:

exports.deleteYesterday = functions.pubsub
    .schedule("0 02 * * *")
    .onRun(async (context) => {
        var yesterday = new Date();
        var dd = String(yesterday.getDate() - 1).padStart(2, "0");
        var mm = String(yesterday.getMonth() + 1).padStart(2, "0"); 
        var yyyy = yesterday.getFullYear();

        const dateString = (yyyy + "-" + mm + "-" + dd).toString();

        let ref = admin.firestore().collection("citas").doc(dateString);
        return ref.delete();
    });

When logging dateString value I get the correct date format I need: dateString

This is how the database looks like: documents

Thanks!!

Upvotes: 0

Views: 154

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317372

Your database screenshot shows that there is no document called "citas/2020-12-02". It was likely already deleted. You can tell because the name of the document is in italics. That italics means that there is no document, but there are nested subcollections organized under it. Those subcollections will not be deleted when you delete the parent document. You will have to write some code to delete all of the documents in the subcollections if you want it to disappear.

See also:

Upvotes: 1

Related Questions