Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To create a subcollection in Firebase Firestore, you can follow these steps:

  1. Get the reference of the parent document to which you want to add a subcollection.
  2. Use the collection() method on the parent reference to get a reference to the new subcollection.
  3. Call the add() method on the subcollection reference to create a new document within the subcollection.

Here's an example code snippet:

// Get a reference to the parent document
const parentDocRef = firebase.firestore().doc('parents/parent1');

// Create a new subcollection reference
const subcollectionRef = parentDocRef.collection('children');

// Add a new document to the subcollection
subcollectionRef.add({
  name: 'Child1',
  age: 10
})
.then((doc) => {
  console.log('Document added with ID: ', doc.id);
})
.catch((error) => {
  console.error('Error adding document: ', error);
});

In this example, we first get a reference to the parent document with a path of 'parents/parent1'. Then, we use the collection() method on the parent reference to get a reference to a new subcollection called 'children'. Finally, we call the add() method on the subcollection reference to create a new document within the subcollection with some sample data.