Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

firebase functions: automatically update fields

In my app I’ve been able to automatically update a single field using firebase function with this code:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const database = admin.firestore();
const path = "ADS/3rVdtNp4RfMXUXFj5ElNOjjcMuT2";
exports.scheduled = functions.pubsub.schedule("* * * * *").onRun((context) => {
  database.doc(path).update({"updateTime": admin.firestore.Timestamp.now()});
  return console.log("Successfully Updated"+admin.firestore.Timestamp.now());
});

This works perfectly as in the picture. But it’s for a single ID.

Picture

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I however, want to write the code that will apply to all the ID’s and any future ID that will that may appear later. I tried the following codes as suggested by someone from this platform almost three years ago. But it didn’t help.

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const database = admin.firestore();
exports.scheduled = functions.pubsub.schedule("* * * * *").onRun((context) => {
  database.collection("ADS").get().then((snapshot) => {
    snapshot.forEach((doc)=>doc.update({t: admin.firestore.Timestamp.now()}));
  });
});

I also used this link but I didn’t really understand it.
link to schedule function

Any help, please?

>Solution :

Instead of updating your document in each loop iteration you should considerate using batch writes.

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const database = admin.firestore();

exports.scheduled = functions.pubsub.schedule("* * * * *").onRun(async (context) => {
  const batch = database.batch()
  const {docs} = await database.collection("ADS").get()
  docs.map(doc => {
    batch.set(
      database.doc(`ADS/${doc.id}`),{
         updateTime: admin.firestore.Timestamp.now()
      }, {
        merge: true
      }
    )
  })

  await batch.commit()
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading