Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore Data Duplication vs storing Document references in fields

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...

like image 454
Anudeep Ananth Avatar asked Sep 13 '25 07:09

Anudeep Ananth


1 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);
    }
}
like image 121
Vinit Khandelwal Avatar answered Sep 15 '25 22:09

Vinit Khandelwal