Firebase Cloud function triggers twice onUpdate

Viewed 2475

I have below rules set for my firebase collection - payments

"payments": {
    "$paymentId": {
        "totalAmount": {
        },
        "balanceAmount": {
            ".validate": "newData.val()<=data.child('totalAmount').val()"
        },
        "paymentDetails": {
            "$detailId": {
                "amount": {
                    ".validate": "newData.isString()"
                },
            }
        },
    }
}

and below cloud function written to handle certain updates on that collection:

exports.calculateBalance = functions.database
.ref('payments/{pushId}')
.onUpdate(event => {
    const paymentRef = event.data.adminRef;
    const payment = event.data.val();
    return paymentRef.once('value').then(snapshot => {
        var paidAmount = 0;
        snapshot.child("paymentDetails").forEach(function(child) {
            paidAmount += parseFloat(child.child("amount").val());
        });
        return paidAmount;
    }).then(snap => {
        payment.balanceAmount = parseFloat(payment.totalAmount) - snap;
        return paymentRef.set(payment);
    })
});

Its simple, whenever I add a payment details, I want to update the balanceAmount. The problem here is, whenever an update occurs at that collection, the function triggers twice. First time its obvious from application and 2nd time its because of paymentRef.set(payment); line.

Is there any possible way I can avoid this 2nd trigger on cloud function? I cannot use any flag on collection level since the update on payment details happens multiple times. Can someone guide me in the right direction on this?

EDIT

Note - I've an edit option for payment details entered.

1 Answers
Related