snapshor.foreach() is not called in Firebase Cloud Firestore v9
P粉041758700
P粉041758700 2024-01-29 14:39:08
0
1
545

I'm trying to delete documents whose value (timestamp) is past 2 hours. I have to call onSnapshot() but not snapshot.foreach() . Checked via console.log; Called1 shows up on the console, but Called2 doesn't. I'm wondering why it's not called to delete the document.

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

reply all(1)
P粉300541798

In Cloud Firestore, each field value is sorted in the index based on its value. In particular, numeric values ​​are sorted earlier in the value index than Timestamp values. Your query for where("Date", "<", cutoffTimestamp) will always return 0 results because it is trying to find Timestamp values ​​that are less than the given number.

To correct this problem, you need to pass a Timestamp or Date value to the where() filter. If you choose to use a Date object, it will be automatically serialized by the SDK to a Timestamp object. This allows you to use what you feel comfortable with.

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

Also, instead of recording "Bidding 1" and "Bidding 2", try the following:

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));
  });
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template