在集合更新中,我设置了onUpdate函数。在该函数中,我尝试对文档发出get请求(使用已更新集合中的数据),然后根据值设置该文档。但是,运行此功能时,它是一致的,有时进行适当的更改,有时不进行更改。当我部署该功能并从冷启动启动时尤其如此。如何确保它返回正确的承诺?
.onUpdate((change, context) => {
const newValue = change.after.data();
const previousValue = change.before.data();
return firestore.collection('A').get()
.then(snapshot => {
snapshot.forEach(doc => {
var docData = doc.data()
if (docData.field1 == context.params.field1) {
var newDocPath = 'B/' + String(docData.field2)
return firestore.doc(newDocPath).get().then(snapshot2 => {
if (snapshot2.data() == undefined) {
return snapshot2.ref.set({
A: 0
})
} else {
return snapshot2.ref.set({
A: parseInt(snapshot2.data().A) + 1
})
}
})
}
})
})
答案 0 :(得分:0)
尝试一下:
.onUpdate((change, context) => {
const newValue = change.after.data();
const previousValue = change.before.data();
return firestore.collection('A').get().then(snapshot => {
var promises = [];
var nDpromises = [];
snapshot.forEach(doc => {
var docData = doc.data()
if (docData.field1 == context.params.field1) {
var newDocPath = 'B/' + String(docData.field2);
const nD = firestore.doc(newDocPath).get().then(snapshot2 => {
if (snapshot2.data() == undefined) {
promises.push(snapshot2.ref.set({A: 0}));
} else {
promises.push(snapshot2.ref.set({A: parseInt(snapshot2.data().A) + 1}));
}
});
nDpromises.push(nD);
}
});
return Promise.all(nDpromises).then(() => {
return Promise.all(promises);
});
});
});