0

我想恢復現有數據,但Firebase雲功能執行循環操作,因此我所做的總結無效。有沒有解決我的問題? 謝謝firebase雲功能函數循環執行

這在我的屏幕拍攝

數據庫建設 image

日誌 image

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; 
    }); 

回答

0

您安裝使用on()方法數據庫引用聽衆。這使得連接監聽器:

你的回調函數會被觸發的初始數據,並再次 每當數據更改

您應該改用once()

偵聽只有一個事件指定事件類型,然後 停止收聽

您的代碼正在循環,因爲您附加了聽衆refUser.on(...),然後在回調中更改該位置處的值:refUser.set(newCount);