【问题标题】:Firestore, query and update with node.jsFirestore,使用 node.js 进行查询和更新
【发布时间】:2021-06-15 15:33:50
【问题描述】:

我需要一个每天自动触发一次的云功能,并在我的“用户”集合中查询“观察”字段为真并将所有这些字段更新为假。在部署我的函数时,我在终端中收到“13:26 错误解析错误:意外的令牌 MyFirstRef”这个错误。 我不熟悉js,所以任何人都可以纠正功能。谢谢。

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})
    })
  })
});

【问题讨论】:

    标签: javascript node.js firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    您的代码中有几点需要更正:

    • 您需要在所有异步作业完成后返回一个 Promise。有关详细信息,请参阅此doc
    • 如果使用await关键字,需要声明函数async,见here
    • QuerySnapshot 有一个forEach() 方法
    • 您只需使用ref 属性即可从QuerySnapshot 获取文档的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()
    
    });
    

    请注意,我们使用 batched write,它最多可以包含 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());
        
    });
    

    【讨论】:

    • 7:92 错误解析错误:Unexpected token =>
    • 第一行以exports开头
    • 你能显示错误对应的确切行吗
    • exports.changeWatched = functions.pubsub.schedule("每 5 分钟").onRun(async (context) => {
    • 感谢您的努力,我真的很感激。
    猜你喜欢
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 2020-08-25
    • 2020-10-01
    • 2019-04-22
    • 2021-11-28
    相关资源
    最近更新 更多