michi07
michi07

Reputation: 105

Firebase Functions: update all documents inside a collection

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.

Upvotes: 7

Views: 7764

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83058

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:

  1. The return in return admin.firestore()....
  2. That in forEach() you get QueryDocumentSnapshots so you have to do doc.ref.update()
  3. The use of 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/

Upvotes: 11

Related Questions