1

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!

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the reply. Now I receive this error: SCRIPT5002: Function expected. ?
I'm also receiving this warning from Firebase in the console: FIREBASE WARNING: Exception was thrown by user callback. TypeError: Function expected.
Can you set up a jsfiddle/jsbin that reproduces the problem? It'll be easier to show you how to fix your code that way.
Thank you very much! The only problem I have now is that it erases the 29 most RECENT messages. Is there a way to order the children in reverse order so that this doesn't occur?? Thank you so much for your help! :)
If you do a search for questions about reversing the order in firebase queries, you will find that the topic has been discussed a lot already.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.