Я хочу иметь функцию, которая удаляет 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
}
}
}
Это как я код мой в течение 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
});
});
Счастливое кодирование!
У вас есть ref.orderByChild('timestamp')
в вашем коде, но в ваших данных нет timestamp
поля. Это интерпретируется как имеющий null
временную метку, которая на самом деле имеет наивысший приоритет в заказе, наложенном Firebase. В результате все ваши узлы данных упорядочиваются до указанного cutoff
и удаляются.
Чтобы решить эту проблему, вам нужно добавить поле timestamp
в вашу схему.
Rollerbanken/{pushId}
?