javascriptfirebasegoogle-cloud-platformgoogle-cloud-firestore

Writing data to a child node in Firestore


When working with 'firebase/firestore' in a React app. I can successfully use code like the one below:

import {collection,addDoc,...} from 'firebase/firestore'

const collectionName = 'France',
      collectionRef = collection(fireStoreDB,collectionName),
      newRcd = await addDoc(collectionRef, {
        sentence: 'To be or not to be ...',
        chapter: 'chapterOne',
        order: 97
      })

In other words the block above writes data to the DB as I expect.

But here is what I would like to do:

const collectionName = 'France/chapterOne',
      collectionRef = collection(fireStoreDB,collectionName),
      newRcd = await addDoc(collectionRef, {
        sentence: 'To be or not to be ...',
        order: 97
      })

Nevertheless, this last piece does not work at this point. This means that if I try to use it, no data is written to the DB. What do I need to modify in the code to make it work?

To be more precise, instead of the data (object with 3 fields) getting stored in one collection(France), I want to have the data (object with 2 fields) stored in one sub-collection(chapterOne) of the collection(France)


Solution

  • I want to have the data (object with 2 fields) stored in one sub-collection(chapterOne) of the collection(France)

    What you're describing isn't possible. Collections are not like directories in a filesystem. In Firestore, collections can't directly contain other subcollections. Collections can only contain documents, which themselves can have other subcollections nested under them.

    If you want a subcollection, you will need at least one intermediate document ID in the path to the subcollection. For example:

    const collectionName = 'France/somedocumentid/chapterOne',
    

    You can create a document with the path France/somedocumentid/chapterOne, which means you will have a top-level collection called "France", a nested document ID under that called "somedocumentid" (the document itself will not exist unless you explicitly create it separately), and a nested subcollection under that ID called "chapterOne".

    You might want to review the documentation Firestore data modeling to better understand how it works.

    Aside, I doubt that your code did more than just "not work". It almost certainly generated an error about the number of segments in the path, which you should be able to see in the web console, assuming that you didn't have additional code to catch and ignore the error.