0

I'm trying to create a new collection, and then create a sub collection all at once. The code is being run when a user creates a new team and adds a players to the team. (both team and player are created/added at the same time) This is what I have attempted so far:

const batch = db.batch()
const collectionRef = db.collection('users').doc(user.uid).collection('teams').doc(id)

batch.set(
  collectionRef.set({
    teamId: id,
    teamName: teamName
  })
)
batch.set(
  collectionRef.collection('players').doc(player.id).set(playerObject)
)
batch.commit().then(()=> {}).catch(err=> console.log(err))

The player object is defined like so:

{
  name: 'John Doe',
  id: '123',
  imgs: ['img.png']
  ...
}

But whenever this runs, only the first write is executed, the sub collection is not created. I think this is because the collection does not exist, so might cause an issue.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
User123123
  • 485
  • 1
  • 5
  • 13

1 Answers1

0

Using firestore Batch is a better approach to do this. Create a batch and add the main document followed by the subcollection document(s).A collection is created once a document is written to it, and removed automatically once the last document is removed from it. If you want to write the collection [parent] and the subcollection [child] in a single batch write, you can do it by generating a UniqueID for the parent document, and then creating the sub collection documents under that same path for example as below:

  • Take a document document under the collection_name collection at the path collection_name/document/

  • And another one sub-collection_name document under the subCollection_name (sub-)collection

    collection_name/document/subCollection_name/sub-collection dcoument
    

Also as mentioned above in the comments from Alex,use reference for the collection object while calling the object in the code to create the path for collection and sub-collection reference path, if the reference object and path is not defined the code will not work.

You may check the below examples for similar implementation:

Vaidehi Jamankar
  • 1,232
  • 1
  • 2
  • 10