Ask Your Question
2

What is the method for creating a subcollection in Firebase Firestore?

asked 2022-04-28 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-11-08 08:00:00 +0000

qstack gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-04-28 11:00:00 +0000

Seen: 13 times

Last updated: Nov 08 '22