【发布时间】:2020-09-22 05:04:56
【问题描述】:
我能够使用 CollectionGroup 访问所有满足条件的子集合文档(记录)。然后我能够在循环中迭代以删除 subCollection 文档。问题,虽然它工作得很好,但却是一个黑客。有没有更好的方法来使用 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”
谢谢!
【问题讨论】:
-
"虽然它工作得很好,但它是一个 hack" - 它不是一个 hack。这正是你应该做的。没有简单的命令可以删除集合或集合组中的所有内容。
-
一如既往地感谢道格!我认为这很笨拙。 path1 := doc.Ref.Parent.Path path2 := path1[0: strings.LastIndex(path1, "myparentCollection")] path3 := strings.Replace(path1, path2, "", -1)
-
既然是这样做的方式,你能把它放在答案中并接受它,以便其他社区成员可以从中受益吗?
-
我刚才做了。谢谢。 fyi-看起来我无法接受自己的解决方案。
-
谢谢!啊,好吧,如果是答案的形式,就已经可以了。