【问题标题】:Firestore sub collection delete oldest in documentFirestore 子集合删除文档中最旧的
【发布时间】:2020-02-17 21:52:32
【问题描述】:

我一直在努力弄清楚如何从子集合中删除文档,只保留最新的 5 个文档。

我首先尝试获取子集合中的文档列表,按'updated' 日期时间戳排序。然而,这返回 null

let updates = await firestore
    .collection('spots')
    .doc(spot.id)
    .collection('spotupdates')
    .orderBy('updated','desc');

然后我尝试从列表中删除最旧的,以确保只剩下 5 个

var cntr = 0;
while(updates.docs.length > 5){
    await firestore
        .collection('spots')
        .doc(spot.id)
        .collection('spotupdates')
        .doc(updates[cntr].id)
        .delete();
    cntr++;
}
cntr = null;

请帮忙 - 真的卡住了

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    根据 Firebase 文档从数据库中删除数据:

    要删除 Cloud Firestore 中的整个集合或子集合, 检索集合或子集合中的所有文档,并且 删除它们。如果您有更大的收藏,您可能需要删除 小批量的文档,以避免内存不足错误。重复 该过程,直到您删除整个集合或 子集合。

    您可以在 this link 中找到简化代码 sn-p 来删除集合和子集合。

    您还可以在 this link 中找到有关删除 Firestore 中的字段、文档和集合的更多信息和详细示例。

    如果这有帮助,请告诉我。

    【讨论】:

    • 谢谢。我以前经历过所有这些,但在我目前的情况下没有帮助。我不会删除整个子集合,也不担心超时等限制,因为它可能在集合中只有 6 个文档。 orderby 是第一个返回 null 的问题
    • @cfl 您是否检查过时间戳字段实际上不为空?
    • 其中一些可以为空,但大部分都已设置。根据文档,那些为空的将不会包含在过滤列表中,即 100%。但整个反应是空的
    【解决方案2】:

    我在我的应用上做了类似的事情,但基于你的数据结构

    首先,获取集合中的所有文档

    const updates = await firestore
                     .collection('spots')
                     .doc(spot.id)
                     .collection('spotupdates')
                     .get()
    

    映射文档数据以返回一个数组

    const updatesArray = updates.docs.map(doc => doc.data())
    

    做逻辑然后删除

    if (updatesArray.length > 5){
                const sorted = updatesArray.sort((a,b) => b.created_at - a.created_at)
                const oldest = sorted.pop()
                await firestore
                 .collection('spots')
                 .doc(spot.id)
                 .collection('spotupdates').doc(oldest.id).delete()
            }
    

    【讨论】:

      猜你喜欢
      • 2018-11-01
      • 2018-03-22
      • 1970-01-01
      • 1970-01-01
      • 2020-01-04
      • 2020-09-08
      • 2018-07-20
      相关资源
      最近更新 更多