Every minute, a script automatically adds a new record to my Firebase database.
I am trying to figure out how to delete the oldest records once the list reaches a certain length.
After researching through documentation and other posts, I have come across the following solution:
// Define the maximum number of records to keep in the chat history.
const MAX_ARDUINO = 10;
exports.arduinoResponseLength = functions.database.ref('/arduinoResponse/{res}').onWrite(event => {
const parentRef = event.data.ref.parent;
return parentRef.once('value').then(snapshot => {
if (snapshot.numChildren() >= MAX_ARDUINO) {
let childCount = 0;
let updates = {};
snapshot.forEach(function(child) {
if (++childCount <= snapshot.numChildren() - MAX_ARDUINO) {
updates[child.key] = null;
}
});
// Update the parent to remove extra children.
return parentRef.update(updates);
}
});
});
The issue with this approach is that onWrite
seems to download all related data each time it is triggered.
While this may work well for smaller lists, I run into problems with my 4000 records as it impacts my Firebase download quota every month.
Is there a more efficient way to handle this situation?