我能够使用CollectionGroup来访问所有满足条件的subCollection文档(记录)。然后,我可以循环访问以删除subCollection文档。问题是,尽管它可以完美运行,但却是一个hack。有没有更好的方法使用Golang在Firestore中删除子集合?
it := clientdb.CollectionGroup("mychildSubcollection").Where(...mycondition).OrderBy("myfield", firestore.Desc).Documents(context.Background())
for {
doc, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
// return err
}
// Strucure of the doc.Ref is --> &{0xc0000d6788 projects/myproj/databases/(default)/documents/myparentCollection/Ki8sr65sKIoZaCviCp/mychildSubcollection/JwvKbuyRTGx5wZaCviCp myparentCollection/Ki8sr65sKIoZaCviCp/mychildSubcollection/JwvKbuyRTGx5wZaCviCp JwvKbuyRTGx5wZaCviCp}
// fmt.Println(doc.Ref.ID)
// fmt.Println(doc.Ref.Path)
// fmt.Println(doc.Ref.Parent.Path)
// fmt.Println(doc.Ref.Parent.ID)
path1 := doc.Ref.Parent.Path
path2 := path1[0: strings.LastIndex(path1, "myparentCollection")]
path3 := strings.Replace(path1, path2, "", -1)
clientdb.Collection(path3).Doc(doc.Ref.ID).Delete(context.Background()) // Regular collection command, to delete the subcollection
}
至少可以减少黑客的攻击,这可能也有帮助->如您所见,doc.Ref提供了三个字段,显示了子集合文档的完整路径[doc.Ref.Path或doc.Ref.Parent.Path] id(doc.Ref.ID),如何访问结构中的中间字段:“ myparentCollection / Ki8sr65sKIoZaCviCp / mychildSubcollection / JwvKbuyRTGx5wZaCviCp”
谢谢!
答案 0 :(得分:0)
以上被接受为解决方案。我要添加的唯一评论是,如果有更好的方法来提取集合的路径,它将更加通用。如您所见,我正在使用实际的集合名称[myparentCollection]来提取路径。效果不错,但一般的效果会更好。
now := time.Now() // start deleting old ones, even ones that still have one second left to expire.
it := clientdb.CollectionGroup("mychildSubcollection").Where("expireafter", "<", now.Add(-1*time.Second)).OrderBy("myfield", firestore.Desc).Documents(context.Background())
for {
doc, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
// return err
}
// Strucure of the doc.Ref is --> &{0xc0000d6788 projects/myproj/databases/(default)/documents/myparentCollection/Ki8sr65sKIoZaCviCp/mychildSubcollection/JwvKbuyRTGx5wZaCviCp myparentCollection/Ki8sr65sKIoZaCviCp/mychildSubcollection/JwvKbuyRTGx5wZaCviCp JwvKbuyRTGx5wZaCviCp}
// fmt.Println(doc.Ref.ID)
// fmt.Println(doc.Ref.Path)
// fmt.Println(doc.Ref.Parent.Path)
// fmt.Println(doc.Ref.Parent.ID)
// using some logic with strings below to get (extract) the collection path example: myparentCollection/Ki8sr65sKIoZaCviCp/mychildSubcollection, so the delete can use it and delete the particular document under the sub collection.
path1 := doc.Ref.Parent.Path
path2 := path1[0: strings.LastIndex(path1, "myparentCollection")]
path3 := strings.Replace(path1, path2, "", -1)
clientdb.Collection(path3).Doc(doc.Ref.ID).Delete(context.Background()) // Regular collection command, to delete the subcollection
}