Home > Mobile >  How to create a collection in FireBase using React
How to create a collection in FireBase using React

Time:03-05

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

CodePudding user response:

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 = colleciton(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 World!',
    })
  }
  • Related