How to Add a Subcollection to a Document in Firebase Cloud Firestore?

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:

Products collection

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:

Reviews subcollection

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 reviews subcollection does not exist yet. It will be created after we execute the addReview() 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.

Review document

Join the Newsletter