我正在努力删除其值(时间戳)在 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();
});
});
}) Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
在 Cloud Firestore 中,每个字段值根据其值在索引中排序。特别是,数字值在值索引中的排序早于
Timestamp值。您对where("Date", "<", cutoffTimestamp)的查询将始终返回 0 个结果,因为它试图查找小于给定数字的Timestamp值。要纠正此问题,您需要将
Timestamp或Date值传递到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)); }); });