程序开发 · 2023年12月9日

Firestore Golang 在事务中使用过滤器运行查询

当前位置: > > > > Firestore Golang 在事务中使用过滤器运行查询

来源:stackoverflow
2024-04-23 22:45:34
0浏览
收藏

哈喽!大家好,很高兴又见面了,我是的一名作者,今天由我给大家带来一篇《Firestore Golang 在事务中使用过滤器运行查询》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!

问题内容

我不知道如何在 golang admin sdk 的事务中运行 firestore.query

firestore.transaction 有一个 getall() 方法,该方法采用 *firestore.documentref 数组,我认为这是在事务中查询多个文档的方式。如果我想查询整个集合,这是有效的,因为我可以使用 tx.documentrefs*firestore.collectionref 转换为文档引用,但似乎没有等效的查询方法(例如,如果我想过滤集合)。

在 nodejs admin sdk 中我可以执行以下操作:

admin.firestore().runTransaction(async (t) => {
  const fooCollectionRef = admin.firestore().collection('foos').where('bar', '==', true);
  const foosSnapshot = await t.get(fooCollectionRef);

  // do stuff with the foos
})

我怎样才能在 golang 中完成同样的事情?

解决方案

使用 transaction.documents 方法。它接受 queryier,它可以是 firestore.query。请参阅文档 中的此方法 下面是一个简单的例子:

err := client.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error {
  col := client.Collection("myCollection")
  query := col.Where("myCondition", "==", 1)
  docs := tx.Documents(query)
  for {
    d, err := docs.Next()
    if err != nil {
      if err == iterator.Done {
        break
      }
      //handle error
    }
    //do something with the document
  }
  return nil
})

if err != nil {
  // handle error.
}

到这里,我们也就讲完了《Firestore Golang 在事务中使用过滤器运行查询》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注公众号,带你了解更多关于的知识点!