Javascript 如何使用云函数计划对Firebase Firestore数据库中的集合进行批量更新?
我不熟悉JS和云功能,我想每天午夜对Firestore数据库中的集合进行更新。我有一个集合Javascript 如何使用云函数计划对Firebase Firestore数据库中的集合进行批量更新?,javascript,node.js,firebase,google-cloud-firestore,google-cloud-functions,Javascript,Node.js,Firebase,Google Cloud Firestore,Google Cloud Functions,我不熟悉JS和云功能,我想每天午夜对Firestore数据库中的集合进行更新。我有一个集合appointmentTimes,其中有一个布尔字段可用,我想每天午夜将其重置为true。到目前为止,我已尝试使用以下方法: const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.resetAppointmentTime
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); });
})
感谢您的任何意见/建议 您可以像cron文件一样使用
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); });
});
不清楚什么是
db.database()
。您应该使用AdminSDK并调用以获取Firebase应用程序实例。此外,您还需要返回承诺链(请观看Firebase视频系列中关于“JavaScript承诺”的3个视频:了解更多详细信息)
下面应该可以做到这一点:
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;
});
})
这在云功能中不起作用,因为服务器实例不能保证在任何时间内保持运行。它们随函数的负载而来又去。你写的有什么问题吗?请将问题编辑清楚。您如何声明数据库?什么是
db.database()
?