[英]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;
請幫忙 - 真的卡住了
我在我的應用程序上做了類似的事情,但基於你的數據結構
首先,獲取集合中的所有文檔
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.