Snap.ref.remove () removes all nodes in the parent, not just itself

I was just trying to delete the top 2 nodes, but it deletes the entire branch instead. If I comment out remove () it correctly console.logs the top 2 nodes, but when I uncomment remove () it removes all nodes in those Ref messages, not just the top 2.

messagesRef.limitToFirst(2).on('child_added', function (snap) {
    snap.ref().remove();
    console.log(snap.val());

});

      

+3


source to share


3 answers


This is because after you removed one of them, there is now a "new" child_added in limit 2. So it will continuously loop through all of them until all of them are removed.

Child 1
Child 2

->>delete child 1

Child 2
Child 3 ->new child_added event

etc...

      



To get around this, you can keep the counter:

var numRemoved = 0; 
var ref = messagesRef.limitToFirst(2);
ref.on('child_added', removeFirstTwoChildren);
removeFirstTwoChildren(snap){
    snap.ref().remove();
    console.log(snap.val());
    numRemoved++;
    if(numRemoved === 2){
        ref.off('child_added', removeFirstTwoChildren);
    }
}

      

+1


source


@MatthewBerg's answer will work great. An alternative, if you only want to delete a few users, is:

var ref = messagesRef.limitToFirst(2);
ref.once('value', function(twovaluesnapshot) {
  twovaluesnapshot.forEach(function(snapshot) {
    snapshot.remove();
  });
});

      



While I generally don't recommend using once

it value

for getting lists of items either , it seems like a reasonable use case.

+1


source


Your messagesRef and messagesRef.limitToFirst (2) .ref () you can check to see the identical path.

What happens if you try the following?

messagesRef.limitToFirst(2).on('child_added', function (snap) {
    console.log(snap.val());
    snap.forEach(function(data) {
        console.log("The message key :" + data.key() );
        messagesRef.child(data.key()).remove();
    });
});

      

0


source







All Articles