Firestore - 如何在 React Native 中通过 id 获取文档

Nod*_*rov 1 javascript firebase react-native google-cloud-firestore

标题说明了一切,当我尝试使用代码从 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);
  });
Run Code Online (Sandbox Code Playgroud)

它向我抛出这个错误:

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

Mor*_*ish 5

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

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

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);
      });
Run Code Online (Sandbox Code Playgroud)