30 分钟后删除 Firebase 文档

Delete Firebase document after 30 minutes

我想在创建 30 分钟后删除 Firebase 中的一些文档。我正在尝试为此使用 Firebase Functions。它总是以某种方式删除文档而不检查日期。这是我的代码。它正在运行,但我不明白为什么我不能检查日期。

exports.scheduledFunction = functions.pubsub.schedule('every 1 minutes').onRun((context) => {
  const now = new Date();
  const queryTime = new Date(now - 30 * 60000);

  const trips = admin.firestore().collection('trips');
  const allTrips = trips.get().then(snapshot => {
    snapshot.forEach(trip => {
      if (trip.data().date < queryTime) {
        admin.firestore().collection('trips').doc(trip.id).delete();
      }
    });
  });

  return allTrips;
});

变量 now 是一个 Date and not a number. Try using Date.now() 来获取当前时间戳:

const queryTime = new Date(Date.now() - 30 * 60000);

然后您可以使用 where() 子句来获取 date 字段早于 30 分钟的文档,而不是获取所有文档并自行过滤掉它们。这将节省许多读取费用,因为您只获取匹配的文档而不是整个集合。

export const scheduledFunction = functions.pubsub
  .schedule("every 1 minutes")
  .onRun(async (context) => {
    // async fn ^^
    const queryTime = new Date(Date.now() - 30 * 60 * 1000);

    // Alternatively:
    // const queryTime = admin.firestore.Timestamp.fromMillis(Date.now() - 30 * 60 * 1000);

    // Query to fetch documents where date is less than queryTime
    const tripsQuery = admin
      .firestore()
      .collection("trips")
      .where("date", "<", queryTime);

    const allTrips = await tripsQuery.get();
 
    // Mapping an array of delete promises
    await Promise.all(allTrips.docs.map((d) => d.ref.delete()));

    return allTrips;
  });

或者,您也可以使用 batched writes 一次删除最多 500 个文档。