最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Firestore - how to get a document by id in React Native - Stack Overflow

programmeradmin3浏览0评论

Title says it all, when I try to get a document by id from Firestore using code:

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

It throws me this error:

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

So I supplied an object with an id: {id: "foo"} which gave me another error:

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

How can I get a document from collection by id?

Title says it all, when I try to get a document by id from Firestore using code:

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

It throws me this error:

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

So I supplied an object with an id: {id: "foo"} which gave me another error:

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

How can I get a document from collection by id?

Share Improve this question edited Jan 18, 2024 at 13:23 soundflix 2,86312 gold badges16 silver badges34 bronze badges asked Aug 3, 2019 at 7:52 N NN N 1,6384 gold badges28 silver badges46 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

The get method of firestore doesn't accept any argument.

You need to pass your id with the doc method, as stated 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);
      });

Get the id and assign to a new {key: value}

See code below

const newProducts = [];
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));       
发布评论

评论列表(0)

  1. 暂无评论