Creating nested documents in firestore


  1. Firestore returning no records yet, I see them in console
  2. Collection not retuning any element.
  3. ... ... 

You might facing issues written above. Then it might be this case.

You might getting empty response in this kind of query though there are elements in firestore.


db.collection(collection1).doc(doc1)
.collection(collection2).doc(doc2)
.collection(collection3).get()
.then(
 function (querySnapshot) {
            querySnapshot.forEach(function (doc) {   
              console.log(doc.id, " = ", doc.data());
 }
)

I face the same problem. Though data was stored sucessfully ( I was guessing, which was wrong actully ).  To verify that your data is not stored as you expceted you can do check this.
Key in italics font means element is deleted
Key in italics font means element is deleted

If key of your data is in italic font then your data is not stored or is marked as deleted [ that was happening in my case ]. See in image.


Now you might thinking, that I have created element and  not deleted it then why it's showing as deleted.

Truth is that if you want to create nested

  • collection ( parent collection )
    • document ( parent docuemnt ) 
    • collection ( child collection ) 
      • document ( child document )

you have to create first parent document and after using its referance you have to create child document.

You should find reson behind this behaviour your self , but for now, perfect way to handle this would be is make sure you code creating documents at every level explicitly.

For example,



var collectoinRef= db.collection(collection1).doc((doc1))
    .collection(collection2).doc(doc2)
    .collection(collection3)

  collectoinRef.doc(doc1)
    .get()
    .then((docSnapshot) => {

      // If document we are going to use as parent document is exist then 
      // we just have to set the child doc inside collectin of that document
      if (docSnapshot.exists) {
         collectoinRef.doc(doc1)
          .collection(collection2)
          .doc({customeid-for-doc}).set(doc)
          .then(() => {
         // Something ....            
          })
     
      // But if document we want to use as parent not exist, Then first we have to 
      // create it.
      // If that document is just used for arragment of elements then just pass empty
      // object set({}) and it will creat empty document for you.
      // After creation of empty parent object you can create collection of child docs 
      // inside it.
     
      } else {
  // Creating empty parent object
         collectoinRef.doc(doc1).set({}).then(() => {
          // creating child object inside parent object
          // after succefull insertion of parent object
          collectoinRef.doc(doc1).collection(collection2)
            .doc({customeid-for-doc}).set(doc)
            .then(() => {
             // Something ....        
            })
        })     
      }
    })

Comments

Popular Posts