Home > OS >  Can I add A Firebase collection in a collection
Can I add A Firebase collection in a collection

Time:10-25

I have a form that collects user information and favourite foods But when collecting favourite food I want the favourite Food collection to be a Child to the 'users' collection Likes:


const sendPosts = (e) => {
e.preventDefault()
db.collection("users").add({

//here I add the user details
name: "userName",
lastName: "userLastName",

//is it possible to also add a collection like this after "lastName"

collection("favFood").add({
favDrink: "userDrink",
favDessert: "userDesert",
          })
        })
      }```


is it possible to do it like that or is it impossible or there is a simple way?

CodePudding user response:

Yes it is possible, since the add() method returns the DocumentReference of the newly created document.

db.collection("users").add({
    name: "userName",
    lastName: "userLastName"
})
.then(userDocRef => {
    userDocRef.collection("favFood").add({
        favDrink: "userDrink",
        favDessert: "userDesert",
    });
});

userDocRef.collection("favFood") declares the CollectionReference of the favFood subcollection of the newly created user document. See the doc.

  • Related