I have the following structure in the Firebase database, where RoomsTemplate is a subscription room. If someone signs up for the Users node, another function (onWrite) increases the value of CountUsers.
and the following function decreases the value of CountUsers when users unsubscribe from node Users.
exports.recountUsers = functions.database.ref('/RoomsTemplate/{id}/CountUsers').onDelete(async (snap) => {
const counterRef = snap.ref;
const collectionRef = counterRef.parent.child('Users');
const messagesData = await collectionRef.once('value');
return await counterRef.set(messagesData.numChildren());
});
The problem is that, if I want to delete the main node of the RoomsTemplate, in this case
-MBb2ZKj-pquagHBqguS
the onDelete function won't let me delete it, but it will update the CountUsers: 0 again. Try deleting the Barrio:"Barcelona" node with another function first and then verify and delete the main node.
exports.recountUsers = functions.database.ref('/RoomsTemplate/{id}/CountUsers').onDelete(async (snap) => {
const counterRef = snap.ref;
const collectionRef = counterRef.parent.child('Users');
const messagesData = await collectionRef.once('value');
const Barrio = await counterRef.parent.child('Barrio').once('value');
if(Barrio.numChildren() === 0){
return await counterRef.remove();
}else if(Barrio.numChildren() > 0){
return await counterRef.set(messagesData.numChildren());
}else{
return null;
}
});
But I still have the same existence problem. How can I permanently delete the main node (-MBb2ZKj-pquagHBqguS), without executing the onDelete function?
