Search code examples
angularfirebase-realtime-databasegoogle-cloud-functionsangular5angularfire2

How to add collection within document + angularfire2 + angular5


I want to add a collection within a document, I searched a lot over google but I haven't found any proper resolution. Even searched firebase documentation but no results for my query.

I have tried different ways to add a collection to a document, below is an example of my code.

let tmpObj = {
  title: vm.pageTitle,
  creationDate: dt.getTime()
};
this.db.collection("pages").doc("page_"+this.bookId).collection("Test").add(tmpObj);

Also, I even tried

let mainCollection = this.db.collection("pages").doc("page_"+ this.bookId).collection("test").valueChanges();
let subcollection = mainCollection.push(tmpObj);
// This is also not working for me

In the above code db is public db: AngularFirestore Please find the attached screenshot to see where I want to add the collection (highlighted it).

Structure I need is Collection -> Document -> Collection

enter image description here


Solution

  • The below code sufficed my needs and with this code now I can create as many nested collections within each documents.

    tmpObj = {
        title: vm.pageTitle,
        desc: description,
        creationDate: dt.getTime()
      }
    
    this.db.collection('pages').doc("pages_"+ this.bookId).collection<any>("AllPages").doc("page_"+ dt.getTime()).set({tmpObj})
    .then(function() {
        console.log("Pages Created successfully!");
    })
    .catch(function(error) {
        console.error("Error writing document: ", error);
    });