Gerrit
Gerrit

Reputation: 31

Update a field from all documents in Firebase

I am very new to Firebase and I am not sure how to update the same field in all documents in one collection.

  return db.collection('collection').get().then((snapshot) => {
    return snapshot.forEach((doc) => {

      doc.update({'field': 1});
      
    });
  })
  .catch((err) => {
    console.log('Error getting documents', err);
  });

I am running this code in a firebase function. There are no errors, but nothing is happening. I can't see anything in the documentation about this specific problem. Does anyone know what's wrong?

Upvotes: 1

Views: 1363

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598708

You'll need to return the result of all the update() calls to the caller, as otherwise it can't know when all asynchronous operations have completed:

  return db.collection('collection').get().then((snapshot) => {
    return Promise.all(snapshot.documents.map((doc) => {
      return doc.ref.update({'field': 1});
    }));
  });

The changes:

  1. return the promise from update() so that it can be bubbled up to the Cloud Functions container.
  2. Use map so that we get an array of promises.
  3. Then use Promise.all so that we only complete (and thus terminate the Cloud Function) when all the updates have completed.

Upvotes: 1

Gerrit
Gerrit

Reputation: 31

This approach did the thing for me... Don't know if this is a proper way (as said I am a beginner)

exports.scheduledFunction2 = functions.pubsub.schedule('every 1 minutes').onRun((context) => {

    return db.collection("collection")
    .get()
    .then(querySnapshot => {
      if (!querySnapshot.empty) {
        for(let i =0;i<querySnapshot.size;i++){

          var queryDocumentSnapshotTest = querySnapshot.docs[i];
          

          queryDocumentSnapshotTest.ref.update({'counter':1});

        }
        
  
        return null;
  
      } else {
       // do nothing
       console.log("No document corresponding to the query!");
        return null;
      }
    });
  
  
   
  });

Upvotes: 0

Related Questions