Firebase:删除子集合中的文档

编程入门 行业动态 更新时间:2024-10-04 01:17:28

Firebase:删除子集合中的<a href=https://www.elefans.com/category/jswz/34/1770955.html style=文档"/>

Firebase:删除子集合中的文档

我有一个“用户”集合,其中包含一个名为“历史”的子集合的文档,我在其中存储完成的游戏文档。这些文件中的每一个都有一个时间戳“lastModified”。我要实现的是一个预定的触发器,它删除所有超过 24 小时的历史文档。 这是我的尝试:

exports.deleteOldHistoryDocuments = functions.pubsub.schedule("every 1 hours").onRun(async (context) => {
    const now = Date.now();
    const cutoff = now - 24 * 60 * 60 * 1000; // 24 hours in milliseconds

    const usersRef = admin.firestore().collection("users");
    const usersSnapshot = await usersRef.get();

    let totalDocsDeleted = 0;

    // Iterate over all user documents
    for (const userDoc of usersSnapshot.docs) {
      console.log("current documents schedule: ");
      const historyRef = userDoc.ref.collection("history");
      const historySnapshot = await historyRef.where("lastModified", "<", cutoff).get();
      const numDocsDeleted = historySnapshot.size;

      if (numDocsDeleted > 0) {
        const batch = admin.firestore().batch();
        historySnapshot.docs.forEach((doc) => {
          batch.delete(doc.ref);
        });

        await batchmit();

        console.log("Deleted ${numDocsDeleted} history documents for user ${userDoc.id}");
        totalDocsDeleted += numDocsDeleted;
      }
    }

    console.log("Total documents deleted: " + totalDocsDeleted);
  });

上面代码的问题是 historySnapshot 查询结果为 0 个文档,即使我确保时间戳早于 24 小时的文档存在。谁能发现我的错误?

回答如下:

我假设历史集合中的字段

lastModified
在firestore中是
TimeStamp
类型。

基于此,

如果你想查询一个TimeStamp,你需要一个JS

Date
Obj。
Date.now()
返回您用来减去 24 小时的数字。您现在需要做的就是将该数字转换回日期对象。

更改此行应该可以解决问题。

let cutOff = new Date(Date.now() - 24 * 60 * 60 * 1000) 

快乐的编码!

更多推荐

Firebase:删除子集合中的文档

本文发布于:2024-05-30 05:12:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770171.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文档   Firebase

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!