Home > Software engineering >  Need to write to collection in a collection in Firebase
Need to write to collection in a collection in Firebase

Time:10-11

I need to change my web app (JavaScript) I use to load products to Firebase Firestore to create a collection ('blue_bottle') in a collection ('promotions'). It use to write straight into a collection ('blue_bottle') which was sharp for time being. What do I have to add to make it write to a collection ('promotions') first, then to collection ('blue_bottle') I can't seem to find very much JavaScript and Firebase reference.

form.addEventListener('submit', (e) => {
e.preventDefault();
db.collection('blue_bottle').add({

Obviously this was the first thing I tried without success:

form.addEventListener('submit', (e) => {
e.preventDefault();
db.collection('promotions').db.collection('blue_bottle').add({

Now it first need to go to a collection ('promotions') please.

Thank you

CodePudding user response:

The Firestore content model is that a document can only exist in a collection, and a subcollection can only exist in a document. There is no way to nest a collection directly under a collection.

To add something under a nested collection under a document, the syntax is:

db.collection('promotions').doc('the parent document').collection('blue_bottle').add({
  ...
})

Or shorter:

db.collection('promotions/the parent document/blue_bottle').add({
  ...
})
  • Related