簡體   English   中英

Firestore 子集合刪除文檔中最舊的

[英]Firestore sub collection delete oldest in document

我一直在努力弄清楚如何從子集合中刪除文檔,只保留最新的 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;

請幫忙 - 真的卡住了

根據 Firebase 用於從數據庫中刪除數據的文檔:

要刪除 Cloud Firestore 中的整個集合或子集合,請檢索集合或子集合中的所有文檔並將其刪除。 如果您有較大的 collections,您可能需要以較小的批次刪除文檔以避免內存不足錯誤。 重復該過程,直到您刪除整個集合或子集合。

您可以在此鏈接中找到刪除 collections 和子集合的簡化代碼片段

您還可以在此鏈接中找到有關在 Firestore 中刪除字段、文檔和 collections 的更多信息和詳細示例

讓我知道這是否有幫助。

我在我的應用程序上做了類似的事情,但基於你的數據結構

首先,獲取集合中的所有文檔

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

Map 文檔數據返回數組

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()
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM