[英]How to get Full Document from firestore including the reference Data populated
[英]How to get nested reference data at ones from Firestore document?
我的 Firestore 数据库中有两个 collections。
首先, users
看起来像这样:
第二,看起来像这样的posts
:
我在post
文档中存储对user
的reference
。 当我想获取post
时,我还想获取users
详细信息。 现在我必须这样做:
const [userPosts, setUserPosts] = useState([]);
useEffect(async function () {
if (initialized && user) {
let snap = await firebase.firestore().collection('posts').where("author", "==", firebase.firestore().collection('users').doc(user)).get();
let docs = snap.docs.map(doc => doc.data());
for (let i = 0; i < docs.length; i++) {
let doc = docs[i];
docs[i] = { ...doc, author: (await doc.author.get()).data().email }
}
setUserPosts(docs);
}
}, [user]);
这种方法的问题是我必须为每个帖子获取用户文档,这不是一个有效的解决方案。
有更好的方法吗?
尽量不要以与传统数据库相同的方式设计数据结构。 Cloud Firestore 是一个 NoSQL,面向文档的数据库,没有表或行。 数据存储为文档,本质上是键值对,包括字符串等原始字段或列表等复杂对象。
文档中的一个很好的例子涉及使用子集合存储消息。 子集合是与特定文档关联的集合。 你可以像这样重组你的数据。
users:
userA:
name: "Donald Duck"
email: mr.duck@example.com
posts:
post1:
date: 2021-02-09
post2:
date: 2021-02-09
userB:
....
var messageRef = db.collection('users').doc('userA')
.collection('posts').doc('post1');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.