首頁  >  問答  >  主體

snapshor.foreach() 不稱為 Firebase Cloud Firestore v9

我正在努力刪除其值(時間戳記)在 2 小時後過去的文件。我必須呼叫 onSnapshot() 但不呼叫 snapshot.foreach() 。透過console.log檢查; Called1 顯示在控制台上,但 Called2 沒有顯示。我想知道為什麼不調用它來刪除文檔。

onMounted(() => {
    const itemsCollectionRef = collection(db, "Bookings");
    const cutoffTimestamp = Date.now() - 2 * 60 * 60 * 1000; // Two hours ago
    const oldItemsQuery = query(
      itemsCollectionRef,
      where("Date", "<", cutoffTimestamp)
    );

    onSnapshot(oldItemsQuery, (snapshot) => {
      console.log('called1');
      snapshot.forEach((doc) => {
        // Delete the document
        console.log('called2');
        db.collection("Bookings").doc(doc.id).delete();
      });
    });
  })

P粉041758700P粉041758700264 天前503

全部回覆(1)我來回復

  • P粉300541798

    P粉3005417982024-01-30 00:29:26

    在 Cloud Firestore 中,每個欄位值根據其值在索引中排序。特別是,數字值在值索引中的排序早於 Timestamp 值。您對 where("Date", "<", cutoffTimestamp) 的查詢將始終傳回 0 個結果,因為它試圖尋找小於給定數字的 Timestamp 值。

    要修正此問題,您需要將 TimestampDate 值傳遞到 where() 篩選器。如果您選擇使用 Date 對象,它將是 由 SDK 自動序列化為 Timestamp 物件。這使您可以使用您覺得舒服的東西。

    const cutoffTimestamp = Timestamp.fromMillis(Date.now() - 2 * 60 * 60 * 1000); // Two hours ago
    // or const cutoffDate = new Date(Date.now() - 2 * 60 * 60 * 1000);
    const oldItemsQuery = query(
      itemsCollectionRef,
      where("Date", "<", cutoffTimestamp)
    );

    此外,不要記錄“叫1”和“叫2”,而是嘗試以下操作:

    onSnapshot(oldItemsQuery, (snapshot) => {
      console.log(`Found ${snapshot.size} documents older than 2h`);
      snapshot.forEach((doc) => {
        // Delete the document
        console.log(`Requesting #${doc.id} be deleted…`);
        deleteDoc(doc.ref) // <-- Modern Firebase SDK equivalent of ref.delete()
          .then(() => console.log(`Deleted #${doc.id} successfully.`))
          .catch((err) => console.error(`Failed to delete #${doc.id}`, err));
      });
    });

    回覆
    0
  • 取消回覆