【问题标题】:Query firestore database for document id查询文件 ID 的 firestore 数据库
【发布时间】:2018-06-01 06:50:53
【问题描述】:

我想在 Firestore 数据库中查询文档 ID。目前我有以下代码:

db.collection('books').where('id', '==', 'fK3ddutEpD2qQqRMXNW5').get()

我没有得到结果。但是当我查询不同的字段时,它可以工作:

db.collection('books').where('genre', '==', 'biography').get()

文档id的名字怎么称呼?

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    试试这个:

    db.collection('books').doc('fK3ddutEpD2qQqRMXNW5').get()
    

    (第一个查询是寻找一个名为“id”的显式用户设置字段,这可能不是您想要的。)

    【讨论】:

    • 嘿,您知道如何获取符合 firestore 查询中提到的某些条件的文档 ID
    • 如果需要多个where case(多个id)怎么办?
    • 在 python 中我得到AttributeError: 'CollectionReference' object has no attribute 'doc'。原来语法是db.collection('books').document('longid').get()
    • @Midhilaj :文档 ID 可能是唯一的吗?
    • @Midhilaj 在我的情况下,我有另一个集合,其中我有每个用户的文档,其中存储满足特定条件的数据。我的条件非常有限,例如哪个用户上传了什么书。
    【解决方案2】:

    您可以按照以下模式通过其id 获取文档:

    firebase
      .firestore()
      .collection("Your collection")
      .doc("documentId")
      .get()
      .then((docRef) => { console.log(docRef.data()) })
      .catch((error) => { })
    

    【讨论】:

      【解决方案3】:

      我有点晚了,但实际上有办法做到这一点

      db.collection('books').where(firebase.firestore.FieldPath.documentId(), '==', 'fK3ddutEpD2qQqRMXNW5').get()
      

      当您处理 firebase 安全规则并且只想查询您被允许访问的记录时,这可能很有用。

      【讨论】:

      • 你能说明firebase.firestore.FieldPath是从什么初始化的吗?
      • 如果其他人正在努力寻找这个导入它的“import { firestore } from 'firebase';”
      • 完美。我将它用于.where(firebase.firestore.FieldPath.documentId(), "in", listOfReferences)
      • 这太棒了。你在哪里看到的?
      • 在 Flutter 中:firestore.collection("collection_name").where(FieldPath.documentId, whereIn: mList).getDocuments();
      【解决方案4】:

      来自Firestore docs 获取文档。

      var docRef = db.collection("cities").doc("SF");
      
      docRef.get().then(function(doc) {
          if (doc.exists) {
              console.log("Document data:", doc.data());
          } else {
              // doc.data() will be undefined in this case
              console.log("No such document!");
          }
      }).catch(function(error) {
          console.log("Error getting document:", error);
      });
      

      【讨论】:

        【解决方案5】:

        您可以使用 __name__ 关键字在查询中使用您的文档 ID。

        你可以写而不是db.collection('books').doc('fK3ddutEpD2qQqRMXNW5').get()

        db.collection('books').where('__name__', '==' ,'fK3ddutEpD2qQqRMXNW5').get()

        在这种情况下,您应该得到一个长度为 1 的数组。

        firebase 文档在规则文档中提到了此功能。 https://firebase.google.com/docs/reference/rules/rules.firestore.Resource

        【讨论】:

        • 这在 prod 或模拟器中使用 Firestore UI 时很方便,因为您不能使用 db.collection('foo').doc('xxxx')
        • 这是我在云功能实现中所需要的,客户端发送文档 ID,我需要使用“in”查询所有文档并获取文档
        • 谢谢伙计,这正是我要找的信息!
        • @DivyanshuNegi 管理 SDK 有一个 getAll() 函数 googleapis.dev/nodejs/firestore/latest/Firestore.html#getAll 我想这就是你要找的。对吗?
        • @JohnGordon 不幸的是,Firebase Web UI 不允许我使用__name__ 创建查询。应用按钮只是灰显:(
        【解决方案6】:

        只是为了澄清这里的混乱

        请记住,您应该使用async/await 来获取数据,无论是获取完整的collection 还是单个doc

        async function someFunction(){
         await db.collection('books').doc('fK3ddutEpD2qQqRMXNW5').get();
        }
        

        【讨论】:

          【解决方案7】:

          2021 年 6 月

          新的v9 modular sdk 可摇树并生成更小的编译应用程序。建议用于所有新的 Firestore 应用。

          import { doc, getDoc } from "firebase/firestore";
          
          const snap = await getDoc(doc(db, 'books', 'fK3ddutEpD2qQqRMXNW5'))
          
          if (snap.exists()) {
            console.log(snap.data())
          }
          else {
            console.log("No such document")
          }
          

          这是基于firestore docs中的示例

          import { doc, getDoc } from "firebase/firestore";
          
          const docRef = doc(db, "cities", "SF");
          const docSnap = await getDoc(docRef);
          
          if (docSnap.exists()) {
            console.log("Document data:", docSnap.data());
          }
          else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
          }
          

          你可以把它变成一个辅助函数

          async function getDocument (coll, id) {
            const snap = await getDoc(doc(db, coll, id))
            if (snap.exists())
              return snap.data()
            else
              return Promise.reject(Error(`No such document: ${coll}.${id}`))
          }
          
          getDocument("books", "fK3ddutEpD2qQqRMXNW5")
          

          【讨论】:

          • 谢谢!这个答案应该更高。
          • 什么是变量 db ?
          • db 是对您的 Firestore 数据库的引用。您可以在Getting Started docs 中查看如何初始化 Firestore
          【解决方案8】:

          虽然每个人都告诉使用.get(),这是完全合理的,但并非总是如此。

          也许您想根据id 过滤数据(例如使用where 查询)。

          这就是您在 Firebase v9 模块化 SDK 中的操作方式:

          import {collection, documentId} from 'firebase/firestore'
          
          const booksRef = collection('books')
          
          const q = query(booksRef, where(documentId(), '==', 'fK3ddutEpD2qQqRMXNW5'))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-07-06
            • 2021-10-22
            • 2020-07-08
            • 2020-09-22
            • 2018-03-21
            • 1970-01-01
            • 1970-01-01
            • 2018-10-22
            相关资源
            最近更新 更多