i’m trying to automatically delete data older than 2 hours in the firebase real-time database, but after typing this code, it returns me a Malformed calls from JS:field sizes are different error.
function reloadDatas() {
const ref = database().ref('messages/');
const now = Date.now();
const cutoff = now - 2 * 60 * 60 * 1000; // 1 minute in milliseconds
const old = ref.orderByChild('timestamp').endAt(cutoff);
old.once('value', function (snapshot) {
snapshot.forEach(function (childSnapshot) {
childSnapshot.ref.remove();
});
});
}
what am I doing wrong?
>Solution :
I didn’t test your code but we can see the following error in the code: The remove() method is asynchronous so you cannot call it in a forEach() loop. One solution is to use Promise.all() in order to call it a variable number of times in parallel.
So, the following shoudl do the trick (untested):
old.once('value', function (snapshot) {
const promises = [];
snapshot.forEach(function (childSnapshot) {
promises.push(childSnapshot.ref.remove());
});
Promise.all(promises)
});