嘿,我是Firebase云功能的新手,我想通过一个字段订购一个存储在firestore中的集合,然后在集合的每个文档中写入“位置”(这应该每60分钟发生一次)。在阅读了文档和Stackoverflow的一些建议之后,我尝试了以下方法。
exports.scheduledFunctionPosition = functions.pubsub.schedule('every 60 minutes').onRun((context) => {
return admin.firestore().collection("example")
.orderBy("number", "desc")
.get()
.then(querySnapshot => {
if (!querySnapshot.empty) {
for(let i =0;i<querySnapshot.size;i++){
var queryDocumentSnapshotTmp = querySnapshot.docs[i];
queryDocumentSnapshotTmp.ref.update({'position':i+1});
}
return null;
} else {
console.log("");
return null;
}
});
由于我的编程技能不太好,因此我尝试了简单的方法,但是我认为异步编程存在问题。该代码非常适合编号最大的文档。但是,如果文档过多,此功能将不会更新最后的文档。有解决方案吗?
该.update()
也是异步的-你可能需要等待它,无论是使用.then()
或切换到async/await
。我的个人风格是这样写的:
exports.scheduledFunctionPosition = functions
.pubsub
.schedule('every 60 minutes')
.onRun(async (context) => {
//will be returning a PROMISE
let QuerySnapshot = await admin.firestore().collection("example")
.orderBy("number", "desc")
.get();
return QuerySnapshot.empty
? (console.log(""), Promise.resolve(null))
: Promise.all( //Promise.all waits for all promises in an array to complete
//returns an array, but we use it for the array of promises
QuerySnapshot.docs.map(async (doc, index) => {
return doc.ref.update({'position':index+1}) //returns a promise
});
});
返回Promise可确保函数等待操作完成。
另请注意,云功能有严格的时间限制-默认值为60秒。如果您有太多记录,它们可能会超时。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句