【问题标题】:Firestore - how to get document by id in react nativeFirestore - 如何在本机反应中通过 id 获取文档
【发布时间】:2019-12-11 16:10:14
【问题描述】:

标题说明了一切,当我尝试使用代码通过 id 从 firestore 获取文档时:

firestore.collection('my_collection').get('foo')
      .then(snapshot => {
        snapshot.forEach(doc => {
          const data = doc.data();
          console.log(doc.id, data);
        });
      })
      .catch(err => {
        console.log('Error getting documents', err);
      });

它抛出了这个错误:

FirebaseError: FirebaseError: Function Query.get() requires its first argument to be of type object, but it was: "foo"

所以我提供了一个带有 id 的对象:{id: "foo"} 这给了我另一个错误:

FirebaseError: FirebaseError: Unknown option 'id' passed to function Query.get(). Available options: source

如何通过 id 从集合中获取文档?

【问题讨论】:

    标签: javascript firebase react-native google-cloud-firestore


    【解决方案1】:

    firestore 的get 方法不接受任何参数。

    您需要使用doc 方法传递您的ID,如here 所述

    firestore.collection('my_collection').doc('foo').get()
          .then(snapshot => {
            snapshot.forEach(doc => {
              const data = doc.data();
              console.log(doc.id, data);
            });
          })
          .catch(err => {
            console.log('Error getting documents', err);
          });
    

    【讨论】:

      【解决方案2】:

      解决方案

      获取 id 并分配给新的{key: value}

      下面是代码

              firestore()
                .collection('products')
                .where('category', 'in', categories)
                .get()
                .then(docs => {
                  docs.forEach(doc => {
                    const data = doc.data()
      
                    // adding new property id with id from Firestore
                    data.id = doc.id
                    
                    newProducts.push(data)
                  })
                  setProducts(newProducts)
                })
                .catch(err => console.log(err))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-09
        • 1970-01-01
        • 1970-01-01
        • 2021-01-28
        • 2020-07-18
        • 2019-05-05
        • 2018-04-23
        相关资源
        最近更新 更多