Firebase – Cloud Function – Deleting data not working

OK I have very limited knowledge of JS/NodeJs so the error may be apparent, but after asking previously had to create a scheduled function I attempted to create a function that would delete all posts that are 4 weeks/30 days old, for testing purposes I made it 1 hour. (Simply because I don't know how to make it minutes)

This is the code I have:

  const CUT_OFF_TIME = 1 * 60 * 60 * 1000;
    exports.scheduledFunction_deleteMyPosts = functions.pubsub.schedule('0 1 * * *').onRun((context) => {
      functions.firestore.document('/myPosts/{userID}/usersPost/{postID}').onWrite(async (change) => {
        const ref = change.after.ref.parent; // reference to the parent
        const now = Date.now();
        const cutoff = (now - CUT_OFF_TIME) / 1000; // convert to seconds
        const oldItemsQuery = ref.orderByChild('date').endAt(cutoff);
        const snapshot = await oldItemsQuery.once('value');
        // create a map with all children that need to be removed
        const updates = {};
        snapshot.forEach(child => {
            updates[child.key] = null;
        });
        // execute all updates in one go and return the result to end the function
        return ref.update(updates);
    });
 });

It deploys successfully, however, nothing happened after one hour or when I hit run now on Google Cloud scheduler. The content I uploaded is well over an hour old.

My database is structured as so

myPosts
  [USERS_ID]
    usersPost
      [POST_ID]
         -The child nodes

Is it not working because I haven't got neither the user's or post's ID? Do I need to perform something like a collection group query?



Read more here: https://stackoverflow.com/questions/64399451/firebase-cloud-function-deleting-data-not-working

Content Attribution

This content was originally published by SwiftUser at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: