繁体   English   中英

Firestore - 如何在本机反应中通过 id 获取文档

[英]Firestore - how to get document by id in react native

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

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 从集合中获取文档?

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

你需要与你通过ID doc的方法,如规定在这里

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);
      });

解决方案

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

下面是 Se 代码

在此处输入图片说明

        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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM