如何在React-native中从Firestore中读取子集合的文档字段 [英] How to read a sub-collection's document fields from Firestore in react-native
问题描述
在本机项目中,尝试从Firebase的Firestore的根级别集合中的文档中读取所有子集合.不太确定要遵循的文档(Web无法执行 getCollections()
/node?).Firebase已导入,我已经从firestore中成功检索了其他数据,但是我从未能够读取子集合数据.这没有使用库 react-native-firebase
(尽管我已经尝试过react-native-firebase,也没有文档化的解决方案)无论如何,我已经尝试过:
Trying to read all sub collections from a document inside a root-level collection from firebase's Firestore in a react-native project. Not too sure which documentation to follow (web-can't do getCollections()
/node?). Firebase is imported and I have successfully retrieved other data from firestore, but never have I been able to read sub collection data. This is not using the library react-native-firebase
(Although I’ve tried with react-native-firebase and it has no documented solution to this either) Regardless, I've tried:
componentDidMount() {
firebase
.firestore()
.collection('users')
.doc(this.props.user.uid)
.getCollections('conversations')
.then(collections => {
collections.forEach(collection => {
alert(collection.id)
})
})
}
以上返回'_ firebase.default.firestore().collection("users").doc(this.props.user.uid).getCollections'未定义
也尝试过:
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
});
});
在上面,可以读取集合ID,但是如何读取文档字段?上面给了我循环结构错误.
in the above, the collection id can be read, but how can the document fields be read? the above gives me cyclic structure errors.
alert(collection.data())
给了我 [object Object]
alert(JSON.stringify(collection.data())
给我循环结构错误
这是消防站:
实际应用中将填充给定用户的所有对话,然后填充给定对话的所有消息.如何在本机项目中从Firestore的所有子集合中读取数据?
The practical application would be populating all conversations for a given user, and then all messages for a given conversation. How Do I read data from all sub collections from Firestore in a react-native project?
推荐答案
要读取子集合文档数据,最终起作用的是:
To read the sub-collection document data what ultimately worked was:
_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"));
});
});
}
更深入地研究文档确实更有帮助
a deeper dive into documentation was indeed more helpful
这篇关于如何在React-native中从Firestore中读取子集合的文档字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!