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.
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()
})
