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...
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With