Reputation: 497
I'm trying to loop through an object in my app and delete old messages after there are 30 messages already in the Database. Here is my code so far:
var ref1 = firebase.database().ref("chatRooms/" + rm + "/messages");
var query = ref1.orderByChild("time");
query.once("value").then(function(l) {
l.forEach(function(d) {
ref1.once("value").then(function(snapshot1) {
var ast = snapshot1.numChildren(); // Getting the number of children
console.log(ast);
if (ast > 29) {
d.remove();
}
});
});
});
The only problem is that I receive the following error for each one:
SCRIPT438: Object doesn't support property or method 'remove'.
If anyone knows how to fix this, or knows of an alternative, I'd appreciate it!
Upvotes: 1
Views: 4713
Reputation: 600120
Your d
is a DataSnapshot
, which represents the value at a given location at some specific time. It cannot be removed directly.
But you can look up the location that the value is from and call remove()
there:
d.ref.remove();
Full working (and simplified) snippet:
function deleteMessages(maxCount) {
root.once("value").then(function(snapshot) {
var count = 0;
snapshot.forEach(function(child) {
count++;
if (count > maxCount) {
console.log('Removing child '+child.key);
child.ref.remove();
}
});
console.log(count, snapshot.numChildren());
});
}
deleteMessages(29);
Live code sample: http://jsbin.com/tepate/edit?js,console
Upvotes: 1