I want to implement a Functions in Firebase but something strange happens when running a Cloud Functions.
All the flow is correct the searches are done well however when I add an update within my "if" the results are duplicated.
When I comment on the line that executes the function:
actualizatatusbroadcast(broad[c].id, cambio);
works correctly but if I let this function run the console.log prints more than once.
my code is as follows
// Import the Firebase SDK for Google Cloud Functions.
' use strict';
import * as functions from 'firebase-functions';
// Import and initialize the Firebase Admin SDK.
const admin = require('firebase-admin');
const nodemailer = require('nodemailer');
admin.initializeApp();
exports.DeleteUserCirculo = functions.database.ref('/users/{pushId}').onUpdate((snapshot, event) => {
var after = snapshot.after.val();
var cambio = after.status;
console.log("El usuario con ID: ", after.id, "se le aplicará la regla ", after.status);
var chats_bg = admin.database().ref('chats/broadcast_group');
chats_bg.on('value', function(snapshot2)
{
let broad = snapshot2.val();
for (let c in broad)
{
console.log("esta es la vuelta", c);
if (broad[c].type == 'broadcast_group' && broad[c].creatorUserId == after.id)
{
console.log("esta es la vuelta dentro del if", c);
actualizatatusbroadcast(broad[c].id, cambio);
}
}
});
return event.eventId;
});
My function is this and what it does is to update the status of the nodes that meet the condition of the "if"
function actualizatatusbroadcast(broad, cambio)
{
const ref = admin.database().ref();
ref.child('chats/broadcast_group/' + broad).update(
{
status: cambio
}
);
}
This is the log if I let the function that performs the update run, you can see how my console.log is printed more than once to stop testing.
If I comment the line that executes the function that performs the update everything is well displayed
The structure of the node where I perform the update is as follows:
I hope someone can help me clarify a little about why this happens and what I am not considering