I have a Firebase database of chatrooms & I would like to delete chatrooms when they get to a certain age(say 12 hours) via HTTPS trigger, or any trigger really. All my chatrooms have a timeCreated attribute, & I found some samples for deleting data but ALL my data gets deleted.
My guess is I'm not navigating to the right path or something. The whole "chat_rooms" node gets deleted, not just the singular old chatroom I want gone.
My nodeJS/Firebase CF code
My database structure
JSON FILE
{
"chat_rooms" : {
"room1" : {
".priority" : "9y1btvc14n",
"g" : "9y1btvc14n",
"l" : [ 33.8696853, -98.534908 ],
"timeCreated" : 1508634704
},
"room A" : {
".priority" : "9y1btvc161",
"chat_messages" : {
"-Kx0d6aU0vfcH3OuOI9X" : {
"Nicholas R Castro" : "haha OMG"
}
},
"g" : "9y1btvc161",
"l" : [ 33.8697009, -98.5349073 ],
"timeCreated" : 1508634797
}
},
"usernames" : {
"Mick Mastro" : "Knx3DCMTTZhDfgU3uBFpRQIQoJr1",
"Rick Dastro" : "Tv6PkDZ2NpX3TPgcqEPg9LNSilR2"
}
}
CloudFunction NodeJs file
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
//the seconds since Jan 1, 1970 midnight
var seconds = new Date().getTime() / 1000;
const chatRoomsRef = functions.database.ref('chat_rooms');
const chatRoomsRef2 = admin.database().ref('chat_rooms');
exports.deletePractice = functions.https.onRequest((req,res)=>{
var resultString = "Deleting these: ";
chatRoomsRef2.once('value')
.then(function(snapshot){
snapshot.forEach(function(childSnapShot){
var roomName = snapshot.key;
var uniqueRoomName = childSnapShot.key;
console.log(roomName); // "chat_rooms"
console.log(childSnapShot.key); // the unique room name
console.log(childSnapShot.child('timeCreated').val());
console.log(seconds);
if( ( seconds - childSnapShot.child("timeCreated").val() ) > 5){
const now = Date.now();
const cutoff = now - 5;
console.log("If statement passed3!");
const oldItemsQuery = chatRoomsRef2.orderByChild('timeCreated').endAt(cutoff);
return oldItemsQuery.once('value').then( snapshot => {
//create a map with all the children need to be removed
const updates = {};
snapshot.forEach(child => {
updates[child.key] = null;
});
return chatRoomsRef2.update(updates);
});
}
});
});
res.status(200).send(resultString);
});

