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(); }); }); })
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 forwhere("Date", "<", cutoffTimestamp)
will always return 0 results because it is trying to findTimestamp
values that are less than the given number.To correct this problem, you need to pass a
Timestamp
orDate
value to thewhere()
filter. If you choose to use aDate
object, it will be automatically serialized by the SDK to a Timestamp object. This allows you to use what you feel comfortable with.