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?
CodePudding user response:
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 should do the trick (untested):
JS SDK v8
old.get().then((snapshot) => {
const promises = [];
snapshot.forEach(function (childSnapshot) {
promises.push(childSnapshot.ref.remove());
});
Promise.all(promises)
});
JS SDK v9
get(old).then((snapshot) => {
const promises = [];
snapshot.forEach(function (childSnapshot) {
promises.push(childSnapshot.ref.remove());
});
Promise.all(promises)
});
Another possibility would be to simultaneously write to the different database nodes with the update()
method and passing null
. See here and here in the doc form more details.