Reputation: 495
On a collection update, I have an onUpdate function set. Within that function I am try to make a get request on a document (using data from the collection that was updated) and then setting that document depending on the values. However, when this function runs, it is consistent, sometimes making the appropriate change, and sometimes not. This is especially the case when I deploy the function and it launches from a cold start. How do I ensure that it returns the correct promise?
.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
})
}
})
}
})
})
Upvotes: 0
Views: 628
Reputation: 1758
Try this:
.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);
});
});
});
Upvotes: 1