I am new to JS and Cloud Functions and I would like to perform an update to a collection in my Firestore database every day at midnight. I have a collection appointmentTimes
with a boolean field available
and I want to reset this to true
every day at midnight. So far I've tried using the following:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.resetAppointmentTimes = functions.pubsub.schedule('0 0 * * *').onRun((context) => {
const appointmentTimesCollectionRef = db.database().collection('appointmentTimes');
appointmentTimesCollectionRef.get().then(querySnapshot => {
if (querySnapshot.empty) {
return null;
} else {
let batch = db.database().batch();
querySnapshot.forEach(doc => {
batch.update(doc.ref, { available: true });
});
return batch.commit();
}
}).catch(error => { console.log(error); });
})
Thank you for any input/suggestions!
It is not clear what is db.database()
. You should use the Admin SDK and call admin.firestore()
to get a Firebase App instance. also, you need to return the Promises chain (watch the 3 videos about "JavaScript Promises" from the Firebase video series: https://firebase.google.com/docs/functions/video-series/ for more details).
The following should do the trick:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
exports.resetAppointmentTimes = functions.pubsub.schedule('0 0 * * *').onRun((context) => {
const appointmentTimesCollectionRef = db.collection('appointmentTimes');
return appointmentTimesCollectionRef.get() // See the return here
.then(querySnapshot => {
if (querySnapshot.empty) {
return null;
} else {
let batch = db.batch();
querySnapshot.forEach(doc => {
batch.update(doc.ref, { available: true });
});
return batch.commit();
}
})
.catch(error => {
console.log(error);
return null;
});
})
You can use node-schedule like a cron file
var schedule = require('node-schedule');
var j = schedule.scheduleJob('0 0 0 * * *', function(){
const appointmentTimesCollectionRef = db.database().collection('appointmentTimes');
appointmentTimesCollectionRef.get().then(querySnapshot => {
if (querySnapshot.empty) {
return null;
} else {
let batch = db.database().batch();
querySnapshot.forEach(doc => {
batch.update(doc.ref, { available: true });
});
return batch.commit();
}
}).catch(error => { console.log(error); });
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.