firebase 云函数函数循环执行

firebase cloud function function looping in execution

我想对现有数据进行恢复,但 Firebase 云函数进行循环,因此我所做的求和无效。我的问题有解决办法吗? 谢谢

这是我的屏幕截图

数据库建设 ,

日志

const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
var db = admin.database();
exports.makePurchaseSummaryAdd = functions.database.ref('/invoice_data/{pushIdInvoice}/item/{pushIdItem}')
    .onCreate(event => {
        var name = event.data.child('itemName').val();
        var quantity = event.data.child('quantity').val();

        var ref = db.ref('/invoice_data/' + event.params.pushIdInvoice + '/idUser');
        ref.on("value", function(snapshot) {
            var refUser = db.ref('/user_data/' + snapshot.val() + '/purchaseSummary/' + name.toUpperCase());
            refUser.on("value", function(snapshotUser) {
                if (snapshotUser.exists()){
                    console.log('Ada Data');
                    var count = snapshotUser.val();
                    var newCount = quantity + count;
                    refUser.set(newCount);
                    console.log('create', count, newCount, name.toUpperCase());
                }
                else {
                    console.log('Tidak Ada Data');
                }
            }, function (errorObject) {
              console.log("The read failed: " + errorObject.code);
            });
        }, function (errorObject) {
          console.log("The read failed: " + errorObject.code);
        });
        return true;
    });

您正在使用 on() 方法附加数据库引用侦听器。这使侦听器附加:

Your callback will be triggered for the initial data and again whenever the data changes

您应该改用 once():

Listens for exactly one event of the specified event type, and then stops listening

您的代码正在循环,因为您附加了一个侦听器 refUser.on(...),然后在回调中更改了该位置的值:refUser.set(newCount);