简体   繁体   中英

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. 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:

  • You need to return a Promise when all the asynchronous job is completed. See this doc for more details.
  • If you use the await keyword, you need to declare the function async , see here .
  • A QuerySnapshot has a forEach() method
  • You can get the 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM