[英]Can't calculate the old and new values difference in Firebase cloud trigger function
This cloud function scans new entries in one collection and adjusts data in the other.此云 function 扫描一个集合中的新条目并调整另一个集合中的数据。
Information from my orders
collection is being sent to cars
collection with their matching reference fields.来自我的
orders
集合的信息正被发送到带有匹配参考字段的cars
集合。 However, the issue appears on the second function that updates data, when adjusting shipping costs it reduces totalSales
with the number it is updated with, rather than the difference between them, meaning that shippingCost is substracting more than it should be.但是,问题出现在更新数据的第二个 function 上,在调整运输成本时,它会减少
totalSales
与它更新的数量,而不是它们之间的差异,这意味着 shippingCost 减去的量超过了应有的量。
I have tried to implement change.before.data
but without any success.我试图实现
change.before.data
但没有任何成功。
The code itself is:代码本身是:
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;
}
);
The issue is that the totalSales
subtract shipping costs as instructed in the code, but some orders may have further shipping cost adjustments, creating an issue of new value being deducted in addition to previous one.问题在于,
totalSales
会按照代码中的说明减去运费,但某些订单可能会进一步调整运费,从而产生一个问题,即除了之前的订单外,还会扣除新的价值。 In this case, I would like to either deduct or add shippingCost
difference to totalSales
field.在这种情况下,我想在
totalSales
字段中扣除或添加shippingCost
差异。
I think you should use onWrite Event instead of onCreate event on your orders collecion which would give you access to change.before.data();
我认为您应该在您的订单集合上使用onWrite Event而不是 onCreate事件,这将使您可以访问
change.before.data();
and change.after.data();
和
change.after.data();
. .
change.before.data();
would help you to access previous value instead of new value being subtracted.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.