【发布时间】:2021-07-13 08:50:03
【问题描述】:
我是 React Native 和 Firebase 的新手,我正在使用 firestore 构建应用程序。
firestore db 的结构如下所示:
AllPosts > Doc(每个帖子) > Field(name,desc, .... , userId="12345")
对于用户
users > doc(每个用户) id 12345 > field(name,desc,etc)
我不知道这是否是设置数据库的最佳方式。但是当我进入帖子屏幕时,我需要加载该帖子的所有数据以及创建帖子的 userId 的数据,但它们位于完全不同的集合中。
我找不到这样做的好方法。 我已经尝试将 userId 字段从 post doc 设置为 const 'fetchUserById' 并基于此执行查询,但我认为这是完全错误的
const [post, setPost] = useState([]);
const [user, setUser] = useState(null);
useEffect(() => {
firebase.firestore()
.collection("allPosts")
.where(firebase.firestore.FieldPath.documentId(), '==', props.route.params.postId)
.get()
.then((snapshot) => {
let data = snapshot.docs.map(doc => {
const data = doc.data();
const id = doc.id;
return { id, ...data }
})
setPost(data)
})
const fetchUserById = post.userId;
firebase.firestore()
.collection('users')
.where(fetchUserById, '==', firebase.firestore.FieldPath.documentId())
.get()
.then((snapshot) => {
if (snapshot.exists) {
setUser(snapshot.data());
}
else {
}
})
},[])
【问题讨论】:
标签: reactjs firebase react-native google-cloud-firestore