uber
uber

Reputation: 5073

How to add another object to a collection?

I am trying to create a function that adds 'bookings' to a firebase document. In the image below, it can be seen that there's already an object inside of the bookings/date. I want to add another one.

This would make it in an array of objects (?)

collection firebase

So far, my attemps have only overwritten what's in there or created a subcollectioin with the name bookings

const bookingObj = {
      ...cartItems[1],
      userId: userObject.uid,
      carro: 'PASSA_CARRO',
      cor: 'PASSAR_COR',
    }

const businessRef = await approvedBusinessService.doc(businessId)
const bookingDateRef = await businessRef.collection('bookings').doc(currentDate) //currentDate: "15/06/2020"
    try {
      bookingDateRef.set(bookingObj) //will create a subcollection
    } catch (error) {
      console.error('error merging Business info')
    }

Previously, I had { merge: true } but that was also not behaving as I wished.

Upvotes: 0

Views: 43

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317362

"bookings" is not a collection, it's a document field. So you can't refer to it using collection(). If you had a subcollection, it would appear very differently in the console. (And it's strongly worth considering making it a subcollection instead of a field, especially if you can add unbounded lists of objects under it.)

If you want to add a new nested field under bookings, you will have to update the document and call out the name of the nested field to update using dot notation.

const businessRef = approvedBusinessService.doc(businessId)
await businessRef.update(`bookings.${currentDate}`, bookingObj)

Upvotes: 1

Related Questions