[英]Firestore, query and update with node.js
我需要一个云 function 每天自动触发一次,并在我的“用户”集合中查询“观察”字段为真并将所有这些字段更新为假。 我在部署 function 时在终端中收到“13:26 错误解析错误:意外令牌 MyFirstRef”这个错误。 我对js不熟悉所以任何人都可以纠正function。 谢谢。
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const { snapshotConstructor } = require("firebase-functions/lib/providers/firestore");
admin.initializeApp();
exports.changeWatched = functions.pubsub.schedule("every 24 hours").onRun((context) => {
const MyFirstRef = admin.firestore().collection("users")
const queryRef = await MyFirstRef.where("watched", "==", true).get().then((snapshot) => {
snapshot.docs.forEach( doc => {
console.log("debug");
const realId = doc.id
const MyRef = await admin.firestore().collection("users").doc(realId)
MyRef.update({watched: false})
})
})
});
您的代码中有几点需要更正:
await
关键字,则需要声明 function async
,请参见此处。QuerySnapshot
有一个forEach()
方法ref
属性,您就可以从QuerySnapshot
中获取DocumentReference
的 DocumentReference。因此,以下应该可以解决问题:
exports.changeWatched = functions.pubsub.schedule("every 24 hours").onRun(async (context) => { // <== See async
const db = admin.firestore();
const batch = db.batch();
const snapshot = await db.collection("users").where("watched", "==", true).get();
snapshot.forEach(doc => {
batch.update(doc.ref, { watched: false });
});
return batch.commit(); // Here we return the Promise returned by commit()
});
请注意,我们使用批量写入,最多可以包含 500 个操作。 如果您需要在一个 Cloud Function 执行中更新更多文档,请使用Promise.all()
或将批次分成几批。
Promise.all()
版本:
exports.changeWatched = functions.pubsub.schedule("every 24 hours").onRun(async (context) => { // <== See async
const db = admin.firestore();
const snapshot = await db.collection("users").where("watched", "==", true).get();
return Promise.all(snapshot.docs.map(doc => doc.ref.delete());
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.