1

The problem is pretty simple. I want to create a document that has a collection in it. An alternative way of wording it would be I need to make a collection in a document.

I need to be able to do this in React.

Visual: collection -> document -> collection

Here is where I need to add the code:

const addUser = async () => {
    await addDoc(usersCollectionRef, {
      name: newName,
      grade: Number(newGrade),
      role: newRole,
      hours: Number(newHours),

      //Collection Creation should go here as this is where I am making the new document.

    })
  }

Note: This is react and not react native

1 Answer 1

6

If I understood you correctly, you want to make a new collection inside the doc you just created in your code above. A collection cannot be empty, therefore you have to put some data inside a document in your collection. One way this can be done is like this:

const usersCollectionRef = collection(db, 'users')

const addUser = async () => {
    const document = await addDoc(usersCollectionRef, {
      name: newName,
      grade: Number(newGrade),
      role: newRole,
      hours: Number(newHours),
    })

    const newCollectionRef = collection(db, 'users', document.id, 'name of new subcollection')

    await addDoc(newCollectionRef, {
        data: 'Hello there World',
    })
  }
Sign up to request clarification or add additional context in comments.

2 Comments

This looks really good but how would I go at accessing the 'document.id'? By the way thank you so much for helping!
I am not completely sure what you are asking for, but if you are asking about how I got the document.id. When adding the first document, I stored that document inside a constant. I can then use the document constant to retrieve the id of the newly added document in my new collection ref. If you want to get the id of any document, you need to store the addDoc in a variable, and then access it later.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.