I'm trying to write a function for Firebase that update all the documents inside a specific collection when another type of document is updated.
functions.firestore.document('/accounts/{accountId}/resources/{resourceId}')
.onUpdate((change, context) => {
const resource = context.params.resourceId;
admin.firestore().collection('/accounts/'+account+'/tasks')
.where('resourceId', '=', resource).get().then(snapshot => {
snapshot.forEach(doc => {
doc.update({
fieldA: 'valueA',
fieldB: 'valueB'
});
});
return true;
})
.catch(error => {
console.log(error);
});
});
This is not working, but i don't know how to do it, it's the first time i make a function for Firebase.
The following should do the trick:
functions.firestore.document('/accounts/{accountId}/resources/{resourceId}')
.onUpdate((change, context) => {
const resource = context.params.resourceId;
return admin.firestore().collection('/accounts/'+account+'/tasks')
.where('resourceId', '=', resource).get().then(snapshot => {
const promises = [];
snapshot.forEach(doc => {
promises.push(doc.ref.update({
fieldA: 'valueA',
fieldB: 'valueB'
}));
});
return Promise.all(promises)
})
.catch(error => {
console.log(error);
return null;
});
});
Note:
return
in return admin.firestore()....
forEach()
you get
QueryDocumentSnapshots
so you have to do doc.ref.update()
Promise.all()
since you execute several asynchronous methods in parallel.As Doug advised in his comment, you should watch the 3 videos about "JavaScript Promises" from the Firebase video series: https://firebase.google.com/docs/functions/video-series/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With