Firestore Data Duplication vs storing Document references in fields

Viewed 572

I am structuring my Data model for Firestore and trying to decide whether to store document references vs Duplicating the data. It looks quite straight forward to retrieve a document from a document resource field and it looks like the client would have to perform much less write operations with document references, Is there something I am missing here... In what circumstances should one choose to duplicate data vs store document references...

2 Answers

The best solution is to do both together. Example, you have two collections - users and their articles. Save each new article in articles collection as well as in a collection inside users and add an extra field to reference to articles. See following example:

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

Without knowing your specific use case, it's impossible to say what's best. But, generally speaking, if you want to reduce the number of gets and overall latency, you should duplicate data. If you want to reduce the total amount of storage and increase latency, use separate documents.

To actually find out what's best, you should be benchmarking and estimating the billing costs using actual or anticipated data about your data.

Related