2016-06-21 62 views
0

我想通过我的应用程序中的对象进行循环,并在数据库中已有30条消息之后删除旧消息。这是我到目前为止的代码:删除Firebase中的对象? (JavaScript)

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

     } 
    }); 
    }); 
}); 

唯一的问题是,我收到各以下错误:

SCRIPT438: Object doesn't support property or method 'remove'.

如果有人知道如何解决这个问题,或可替代的人都知道,我'欣赏它!

回答

0

您的dDataSnapshot,它表示在某个特定时间给定位置的值。它不能直接删除。

但你可以查找该值是从位置和通话remove()有:

d.ref.remove(); 

全部工作(和简化的)片段:

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

直播代码示例:http://jsbin.com/tepate/edit?js,console

+0

感谢您的回复。现在我收到此错误:SCRIPT5002:函数预期。 ? – Collin

+0

我也在控制台中收到来自Firebase的此警告:** FIREBASE警告:用户回调抛出异常。 TypeError:预期的功能**。 – Collin

+0

你可以设置一个jsfiddle/jsbin来重现问题吗?向您展示如何以这种方式修复您的代码会更容易。 –