我想要一个删除10个小时孩子的功能。到目前为止我有这个代码但是,如果我将其部署到Firebase云功能,它会立即从数据库中删除所有数据。我不确定我做错了什么。请帮忙!
exports.deleteOldItems = functions.database.ref('Rollerbanken/{pushId}')
.onWrite(event => {
var ref = event.data.ref.parent; // reference to the items
var now = Date.now();
var cutoff = now - 10 * 60 * 60 * 1000;
var oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff);
return oldItemsQuery.once('value', function(snapshot) {
// create a map with all children that need to be removed
var updates = {};
snapshot.forEach(function(child) {
updates[child.key] = null
});
// execute all updates in one go and return the result to end the function
return ref.update(updates);
});
});
我的Firebase数据库结构:
{
"Rollerbanken" : {
"-Ku_Ywh8wElDdwNqa0KW" : {
"Extrainformatie" : "",
"Latitude" : "51.8306880305073",
"Longitude" : "5.90483402833892",
"Staater" : "Staat er nog steeds",
"Staaternietmeer" : "",
"Stad" : "Nijmegen",
"Tijd" : "19:50",
"TijdControle" : "19:50",
"TijdControleniet" : "",
"TypeControle" : "Rollerbank",
"TypeControle2" : "Rollerbank",
"postKey" : "-Ku_Ywh8wElDdwNqa0KW",
"timestamp" : 1506016223000
}
}
}
答案 0 :(得分:0)
您的代码中有ref.orderByChild('timestamp')
,但您的数据中没有timestamp
字段。这被解释为具有null
时间戳,其实际上具有Firebase强加的ordering中的最高优先级。因此,所有数据节点都在指定的cutoff
之前排序,并被删除。
要解决此问题,您需要将timestamp
字段添加到架构中。
答案 1 :(得分:0)
这是我24小时编码的方式。
exports.deleteOldItems = functions.database.ref('/notification/{user_id}/{notification_id}').onWrite((change) => {
const ref = change.after.ref.parent; // reference to the parent
// For easier cross browser solution, get old time like this
const yesterday = Date.now() - 86400000; // that is: 24 * 60 * 60 * 1000
const oldItemsQuery = ref.orderByChild('time').endAt(yesterday);
return oldItemsQuery.once('value').then((snapshot) => {
// create a map with all children that need to be removed
const updates = {};
snapshot.forEach(child => {
updates[child.key] = null;
});
return ref.update(updates);
// execute all updates in one go and return the result to end the function
});
});
编码愉快!