簡體   English   中英

無法計算 Firebase 雲觸發器 function 中的新舊值差異

[英]Can't calculate the old and new values difference in Firebase cloud trigger function

此雲 function 掃描一個集合中的新條目並調整另一個集合中的數據。

來自我的orders集合的信息正被發送到帶有匹配參考字段的cars集合。 但是,問題出現在更新數據的第二個 function 上,在調整運輸成本時,它會減少totalSales與它更新的數量,而不是它們之間的差異,這意味着 shippingCost 減去的量超過了應有的量。

我試圖實現change.before.data但沒有任何成功。

代碼本身是:

  exports.useWildcard = functions.firestore
        .document('orders/{docId}')
        .onCreate((change, context) => 
        {
            var tasks = new Promise((resolve, reject) => {
                admin.firestore().collectionGroup('cars').where("carRef","==",change.data().sku).get().then(documents => {
                    docID = '';
                    documents.forEach((doc) => {                  
                        docID = doc.id;
                        totalSales = 0;
                        orderPrice = 0;
                        shippingCost = 0;
                        if(typeof doc.data().totalSales != "undefined")
                            totalSales = parseFloat(doc.data().totalSales);                        
                        if(typeof change.data().orderPrice != "undefined")
                            orderPrice = parseFloat(change.data().orderPrice);                        
                        if(typeof change.data().shippingCost != "undefined")
                            shippingCost = parseFloat(change.data().shippingCost);
                        newTotalSales = totalSales-shippingCost;
                        admin.firestore().collection('cars').doc(docID).update({"totalSales":newTotalSales}).then(documents => {
                            resolve();
                        });
                    });
                    if(docID=='') resolve();
                });
            });
            return tasks;                       
       }
    );

問題在於, totalSales會按照代碼中的說明減去運費,但某些訂單可能會進一步調整運費,從而產生一個問題,即除了之前的訂單外,還會扣除新的價值。 在這種情況下,我想在totalSales字段中扣除或添加shippingCost差異。

我認為您應該在您的訂單集合上使用onWrite Event而不是 onCreate事件,這將使您可以訪問change.before.data(); change.after.data(); .

  • change.before.data(); 將幫助您訪問以前的值,而不是減去新值。

如果您需要更多信息,請檢查此項

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM