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. I get "13:26 error Parsing error: Unexpected token MyFirstRef" this error in my terminal while deploying my function. I am not familiar with js so can anyone please correct 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 .QuerySnapshot
has a forEach()
method DocumentReference
of a doc from the QuerySnapshot
just by using the ref
property.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. In case you need to update more docs in one Cloud Function execution, use Promise.all()
or cut the batch in several batches.
Promise.all()
version:
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());
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.