在 Firebase 中删除对象? (JavaScript)
Remove Object in Firebase? (JavaScript)
我正在尝试遍历我的应用程序中的一个对象,并在数据库中已有 30 条消息后删除旧消息。到目前为止,这是我的代码:
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'.
如果有人知道如何解决这个问题,或者知道替代方案,我将不胜感激!
您的 d
是一个 DataSnapshot
,代表某个特定时间给定位置的值。无法直接删除。
但是您可以查找该值的来源位置并在那里调用 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);
我正在尝试遍历我的应用程序中的一个对象,并在数据库中已有 30 条消息后删除旧消息。到目前为止,这是我的代码:
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'.
如果有人知道如何解决这个问题,或者知道替代方案,我将不胜感激!
您的 d
是一个 DataSnapshot
,代表某个特定时间给定位置的值。无法直接删除。
但是您可以查找该值的来源位置并在那里调用 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);