I would like to delete files from my storage.
And for that I need the UID from the request ref.orderByChild('timestamp').endAt(cutoff);
I already have a function for deleting child nodes, but I want to delete at the same time the picture in my storage.
Screenshot of my database :
My cloud functions for Firebase ( I found the code here Delete firebase data older than 2 hours and here https://github.com/firebase/functions-samples/tree/master/delete-old-child-nodes ) :
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access Cloud Firestore.
var admin = require("firebase-admin");
var serviceAccount = require("./serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://XXXXXX.firebaseio.com",
storageBucket: "gs://XXXXX.appspot.com",
});
var defaultStorage = admin.storage();
// Cut off time. Child nodes older than this will be deleted.
const CUT_OFF_TIME = 24 * 60 * 60 * 1000; // 24 Hours in milliseconds.
/**
* This database triggered function will check for child nodes that are older than the
* cut-off time. Each child needs to have a `timestamp` attribute.
*/
exports.deleteOldItems = functions.database.ref('/images/{pushId}').onWrite(async (change) => {
const ref = change.after.ref.parent; // reference to the parent
const now = Date.now();
const cutoff = now - CUT_OFF_TIME;
const oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff);
const snapshot = await oldItemsQuery.once('value');
// EDIT#2
snapshot.forEach((child) => {
const uid = child.key;
const re = admin.database().ref('images/'+uid);
const img = re.child('image');
const bucket = defaultStorage.bucket();
const file = bucket.file(img);
// Delete the file
return file.delete();
})
// END EDIT#2
// 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);
});
I have already tried to get the value of "image" but I have No such object: XXXXX.appspot.com/https://XXXXX.firebaseio.com/images/undefined/image
Thank you in advance for your help.
EDIT#1
Thanks to Doug Stevenson, I changed the value of "image" for having the good path.
EDIT#2
Thank you Ralemos, I iterate it with a foreach but now I have a new error : Error: No such object: XXXXX.appspot.com/https://XXXXX.firebaseio.com/images/-M9OeGPXB-KqEVqxZYCb/image And I don't understand why because the value is not null.