簡體   English   中英

使用 node.js 進行 Firestore、查詢和更新

[英]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})
    })
  })
});

您的代碼中有幾點需要更正:

  • 完成所有異步作業后,您需要返回 Promise。 有關更多詳細信息,請參閱此 文檔
  • 如果使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM