如何使用 Cloud Functions 计划对 Firebase Firestore 数据库中的集合进行批量更新?



我是JS和Cloud Functions的新手,我想每天午夜对Firestore数据库中的集合进行更新。我有一个带有布尔字段available的集合appointmentTimes,我想将其重置为每天午夜true。到目前为止,我已经尝试使用以下方法:

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); });
})

感谢您的任何意见/建议!

目前尚不清楚db.database()是什么。您应该使用管理员 SDK 并调用admin.firestore()来获取 Firebase 应用实例。此外,您需要返回承诺链(观看 Firebase 视频系列中关于"JavaScript 承诺"的 3 个视频:https://firebase.google.com/docs/functions/video-series/了解更多详情(。

以下应该可以解决问题:

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;
});
})

你可以像使用 cron 文件一样使用 node-schedule

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); });
});

最新更新