Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 324
michi07 Avatar asked Dec 18 '18 15:12

michi07


1 Answers

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/

like image 189
Renaud Tarnec Avatar answered Sep 27 '22 21:09

Renaud Tarnec