如何在 react-native 中从 Firestore 读取子集合的文档字段

How to read a sub-collection's document fields from Firestore in react-native

尝试从反应本机项目中的 firebase 的 Firestore 的根级集合中的文档中读取所有子集合。不太确定要遵循哪个文档(web-can't do getCollections() /node?)。 Firebase 已导入,我已成功从 firestore 中检索到其他数据,但我从未能够读取子集合数据。这没有使用库 react-native-firebase(虽然我已经尝试过使用 react-native-firebase 并且它也没有记录解决方案)无论如何,我已经尝试过:

componentDidMount() {
    firebase
      .firestore()
      .collection('users')
      .doc(this.props.user.uid)
      .getCollections('conversations')
      .then(collections => {
        collections.forEach(collection => {
          alert(collection.id)
        })
      }) 
}

以上returns'_firebase.default.firestore().collection("users").doc(this.props.user.uid).getCollections' is undefined

也试过:

componentDidMount() {
    firebase
      .firestore()
      .collection("users")
      .doc(this.props.user.uid)
      .collection("conversations")
      .get()
      .then(collections => {
        collections.forEach(collection => {
          alert(JSON.stringify(collection)); //collection.id is can be read here
        });
      });

上面可以读取collection id,但是怎么读取document fields呢?以上给了我循环结构错误。

alert(collection.data()) 给我 [object Object]

alert(JSON.stringify(collection.data()) 给我循环结构错误

这里是 firestore:

实际应用程序将填充给定用户的所有对话,然后是给定对话的所有消息。 如何在 react-native 项目中从 Firestore 的所有子集合中读取数据?

你好试试下面的

async _getUserDataFromFirestore() {
        try {
          const ref = firebase
            .firestore()
            .collection('user')
            .doc(this.props.user.uid);
          await ref.get().then(userData => {
           console.log('User details of userID - ' + this.props.user.uid , userData.data());
          });  
        } catch (err) {
          console.log('Error while getting user data from firestore : ', err);
        }
      }

componentDidMount

中添加调用此函数

读取子集合文档数据最终起作用的是:

_getConversation() {
    firebase
      .firestore()
      .collection("users")
      .doc(this.props.user.uid)
      .collection("conversations")
      .get()
      .then(querySnapshot => {
        querySnapshot.forEach(queryDocumentSnapshot => {
          alert(queryDocumentSnapshot.get("members"));
        });
      })
      .catch(err => {
        alert(err);
      });
  }

_getMessages() {
    firebase
      .firestore()
      .collection("users")
      .doc(this.props.user.uid)
      .collection("conversations")
      .doc("some-document-id-here")
      .collection("messages")
      .get()
      .then(querySnapshot => {
        querySnapshot.forEach(queryDocumentSnapshot => {
          alert(queryDocumentSnapshot.get("content"));
        });
      });
  }

深入研究文档确实更有帮助