[英]Firestore, query and update with node.js
I need a cloud function that triggers automatically once per day and query in my "users" collection where "watched" field is true and update all of them as false.我需要一个云 function 每天自动触发一次,并在我的“用户”集合中查询“观察”字段为真并将所有这些字段更新为假。 I get "13:26 error Parsing error: Unexpected token MyFirstRef" this error in my terminal while deploying my function.我在部署 function 时在终端中收到“13:26 错误解析错误:意外令牌 MyFirstRef”这个错误。 I am not familiar with js so can anyone please correct function.我对js不熟悉所以任何人都可以纠正function。 Thanks.谢谢。
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})
})
})
});
There are several points to correct in your code:您的代码中有几点需要更正:
await
keyword, you need to declare the function async
, see here .如果使用await
关键字,则需要声明 function async
,请参见此处。QuerySnapshot
has a forEach()
method QuerySnapshot
有一个forEach()
方法DocumentReference
of a doc from the QuerySnapshot
just by using the ref
property.只需使用ref
属性,您就可以从QuerySnapshot
中获取DocumentReference
的 DocumentReference。The following should therefore do the trick:因此,以下应该可以解决问题:
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()
});
Note that we use a batched write , which can contain up to 500 operations.请注意,我们使用批量写入,最多可以包含 500 个操作。 In case you need to update more docs in one Cloud Function execution, use Promise.all()
or cut the batch in several batches.如果您需要在一个 Cloud Function 执行中更新更多文档,请使用Promise.all()
或将批次分成几批。
Promise.all()
version: 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.