Del*_*iri 1 go google-cloud-firestore
使用 go 和 firestore 创建 Web 应用程序。我遇到了一个奇怪的问题。如果我使用 NewDoc 方法保存数据
ref := client.Collection("blogs").NewDoc()
_, err := ref.Set(ctx, mapBlog)
if err != nil {
// Handle any errors in an appropriate way, such as returning them.
log.Printf("An error has occurred: %s", err)
}
Run Code Online (Sandbox Code Playgroud)
我有能力使用以下方法检索整个集合
var bs models.Blogs
iter := client.Collection("blogs").Documents(ctx)
for {
var b models.Blog
doc, err := iter.Next()
if err != nil {
fmt.Println(err)
}
if err == iterator.Done {
break
}
if err := doc.DataTo(&b); err != nil {
fmt.Println(doc.Data())
bs = append(bs, b)
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当我只想查找博客集合中的所有文档时,这非常有用。但后来我遇到了无法从博客集合中查询特定博客的问题。我通过查看文档并保存这样的帖子解决了这个问题。
//p is a struct and p.ID is just a string identifier
// the docs show creating a struct with an ID and then an embedded struct within.
_, err := client.Collection("blogs").Doc(p.ID).Set(ctx, p)
if err != nil {
fmt.Println(err)
}
Run Code Online (Sandbox Code Playgroud)
但由于我自己创建 docID,因此我使用以下命令从整个集合中检索所有文档
if err := doc.DataTo(&b); err != nil {
fmt.Println(doc.Data())
bs = append(bs, b)
fmt.Println(b)
}
Run Code Online (Sandbox Code Playgroud)
不再有效。基本上,我需要能够加载一页的所有博客,然后如果单击某个特定博客,我需要能够获取 ID 并仅在集合中查找一个文档。如果我自己设置文档 ID,为什么 doc.DataTo 不起作用?
有没有更好的方法来通常从集合中提取所有文档,然后专门提取单个文档?
doc.DataTo(&b)仅当返回错误时,程序才会将博客附加到结果中。
像这样编写代码:
var bs models.Blogs
iter := client.Collection("blogs").Documents(ctx)
defer iter.Stop() // add this line to ensure resources cleaned up
for {
doc, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
// Handle error, possibly by returning the error
// to the caller. Break the loop or return.
... add code here
}
var b models.Blog
if err := doc.DataTo(&b); err != nil {
// Handle error, possibly by returning the error
// to the caller. Continue the loop,
// break the loop or return.
... add code here
}
bs = append(bs, b)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2934 次 |
| 最近记录: |