2015-05-14 15 views

回答

1

這是因爲一旦你刪除一個,現在有一個「新」 child_added成2.因此,它會不斷地循環通過他們所有,直到他們被全部刪除了極限。

Child 1 
Child 2 

->>delete child 1 

Child 2 
Child 3 ->new child_added event 

etc... 

要解決這個問題,你可以保留一個計數器:

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); 
    } 
} 
0

你messagesRef和messagesRef.limitToFirst(2).ref()你可以檢查看到相同的路徑。

當您嘗試以下操作時會發生什麼?

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(); 
    }); 
}); 
1

@ MatthewBerg的回答會是不錯的。如果你只是想去掉一些用戶的替代方案是:

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

雖然我一般不鼓勵爲獲取項目列表的使用oncevalue,這似乎是一個合理的使用情況吧。

相關問題