我正在为 Firestore 构建我的数据模型,并试图决定是存储文档引用还是复制数据。从文档资源字段中检索文档看起来非常简单,而且看起来客户端对文档引用执行的写操作要少得多,我在这里遗漏了什么……在什么情况下应该选择复制数据与存储文档引用...
最佳答案
最好的解决方案是两者同时进行。例如,您有两个集合 - 用户和他们的文章。将每篇新文章保存在文章集合以及用户内部的集合中,并添加一个额外的字段来引用文章。请参阅以下示例:
export const addUserArticle = async (userId, state) => {
const { title, article } = state;
const createdAt = new Date();
const articleRef = firestore.collection("articles").doc();
try {
await articleRef.set({
title: title,
body: body,
createdAt: createdAt,
createdBy: firebase.firestore().doc(`/users/${userId}`)
});
} catch (err) {
console.error("Error saving article to articles in database:", err.message);
}
const userArticleRef = firestore.collection("users").doc(userId).collection(articles).doc(articleRef.id);
try {
await userArticleRef.set({
title: title,
body: body,
createdAt: createdAt,
articleRef: firebase.firestore().doc(`/articles/${articleRef.id}`)
});
} catch (err) {
console.error("Error saving article to user in database:", err.message);
}
}
关于firebase - Firestore 数据复制与在字段中存储文档引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58545154/