snapshor.foreach() wird in Firebase Cloud Firestore v9 nicht aufgerufen
P粉041758700
P粉041758700 2024-01-29 14:39:08
0
1
497

Ich versuche, Dokumente zu löschen, deren Wert (Zeitstempel) mehr als 2 Stunden beträgt. Ich muss onSnapshot() aufrufen, aber nicht snapshot.foreach() . Über console.log überprüft; Called1 wird auf der Konsole angezeigt, Called2 jedoch nicht. Ich frage mich, warum es nicht heißt, das Dokument zu löschen.

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粉041758700
P粉041758700

Antworte allen(1)
P粉300541798

在 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", "

此外,不要记录“叫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) //  console.log(`Deleted #${doc.id} successfully.`))
      .catch((err) => console.error(`Failed to delete #${doc.id}`, err));
  });
});
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!