By Hemanta Sundaray on 2023-01-07
Imagine that you are modeling data for an e-commerce application. You have a products collection in Firestore:
After buying a product, customers have the option to review and share their feedback. You want to save the reviews as a subcollection inside the respective documents inside the products collection:
Unfortunately, the Firebase documentation does not have an example showing how to add a subcollection to a document. However, after some trial and error, I figured it out. Here is the code:
const addReview = async (productId, userId, rating, review) => {
const reviewRef = doc(collection(db, "products", productId, "reviews"))
await setDoc(reviewRef, {
id: reviewRef.id, // Assign the autogenerated ID of the review document to the 'id' field
userId,
productId,
rating,
review,
})
}
In the addReview() function above, the most important piece of code is on line no 2, where we are creating a reference to a document (with an id that matches productId) in a subcollection called reviews within the products collection.
Keep in mind that the
reviewssubcollection does not exist yet. It will be created after we execute theaddReview()function. Note that you can give the subcollection any name you choose.
After creating the reference, we are using the setDoc function to create a new document in the reviews subcollection with the provided data (userId, productId, rating & review).
Once you run the addReview() function, you will have a reviews subcollection with review documents inside it.