【问题标题】:Firestore Data Duplication vs storing Document references in fieldsFirestore 数据复制与在字段中存储文档引用
【发布时间】:2019-10-24 16:03:38
【问题描述】:

我正在为 Firestore 构建我的数据模型,并尝试决定是存储文档引用还是复制数据。从文档资源字段中检索文档看起来很简单,看起来客户端必须对文档引用执行更少的写入操作,这里有什么我遗漏的东西......在什么情况下应该选择复制数据与存储文档引用...

【问题讨论】:

    标签: firebase google-cloud-firestore


    【解决方案1】:

    最好的解决方案是同时进行。例如,您有两个集合 - 用户和他们的文章。将每篇新文章保存在文章集合以及用户内部的集合中,并添加一个额外的字段来引用文章。请参见以下示例:

    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);
        }
    }
    

    【讨论】:

      【解决方案2】:

      如果不了解您的具体用例,就不可能说出什么是最好的。但是,一般来说,如果您想减少获取次数和总体延迟,您应该复制数据。如果您想减少总存储量并增加延迟,请使用单独的文档。

      要真正找出最好的方法,您应该使用有关数据的实际或预期数据进行基准测试和估算计费成本。

      【讨论】:

      • 嗨,Doug,这是可能的用例... Collection A-> B.Document->C.Sub-Collection->D.Document with 5 fields->E.Sub-Collection - > F.文档 || Collection B ->2.Document->3.Sub-Collection-> case 1: 4.Document-> Field type reference to D.Document or case 2: 4.Duplicate copy of D.Document。集合 A 和 B 将由两个不同的客户端读取
      • 这并没有什么帮助,因为它不是很具体,所以仍然建议使用实际或预期数据进行基准测试和估计。
      猜你喜欢
      • 2022-12-04
      • 2019-03-09
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      • 2020-10-01
      • 1970-01-01
      相关资源
      最近更新 更多