[英]Firestore sub collection delete oldest in document
I've been struggling with figuring out how to delete documents from a sub collection, keep only the latest 5 documents.我一直在努力弄清楚如何从子集合中删除文档,只保留最新的 5 个文档。
I firstly try and get a list of documents in the sub collection, ordered by 'updated'
date timestamp.我首先尝试获取子集合中的文档列表,按
'updated'
日期时间戳排序。 This however returns null然而,这会返回 null
let updates = await firestore
.collection('spots')
.doc(spot.id)
.collection('spotupdates')
.orderBy('updated','desc');
I then try and delete the oldest from the list, to ensure only 5 remain然后我尝试从列表中删除最旧的,以确保只剩下 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;
Please help - really stuck请帮忙 - 真的卡住了
According to Firebase Documentation for deleting data from your database:根据 Firebase 用于从数据库中删除数据的文档:
To delete an entire collection or subcollection in Cloud Firestore, retrieve all the documents within the collection or subcollection and delete them.
要删除 Cloud Firestore 中的整个集合或子集合,请检索集合或子集合中的所有文档并将其删除。 If you have larger collections, you may want to delete the documents in smaller batches to avoid out-of-memory errors.
如果您有较大的 collections,您可能需要以较小的批次删除文档以避免内存不足错误。 Repeat the process until you've deleted the entire collection or subcollection.
重复该过程,直到您删除整个集合或子集合。
You may find a simplified code snippet to delete collections and subcollections in this link .您可以在此链接中找到删除 collections 和子集合的简化代码片段。
Also you will find more information and detailed examples about deleting fields, documents and collections in Firestore in this link .您还可以在此链接中找到有关在 Firestore 中删除字段、文档和 collections 的更多信息和详细示例。
Let me know if this was helpful.让我知道这是否有帮助。
I did something similar on my app but based on your data structure我在我的应用程序上做了类似的事情,但基于你的数据结构
First, get all the documents in the collection首先,获取集合中的所有文档
const updates = await firestore
.collection('spots')
.doc(spot.id)
.collection('spotupdates')
.get()
Map the document data to return an array Map 文档数据返回数组
const updatesArray = updates.docs.map(doc => doc.data())
Do logic then delete做逻辑然后删除
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.