3

I would like to update the completed property of an object in an array in Firestore, but I have no idea how to reach that specific element in the array. The image will show the structure.

enter image description here

I have come up this far but don't know how to choose, for example, item 1 in the array. I was thinking of using its ID (it has an id property) but don't know how to get there.

const businessRef = db.collection('approvedBusinesses').doc(businessId)
      try {
        businessRef.update({
          [`bookings.${currentDate} ????? `]: true // what to add after currentDate?
        })

By the way, this is how the array was created (and how other objects are pushed to it)

const bookingObj = {
      carro: 'PASSA_CARRO',
      completed: false,
      userId: userObject.uid,
    }

businessRef.update({
        [`bookings.${currentDate}`]: firebase.firestore.FieldValue.arrayUnion(bookingObj),
      })
uber
  • 4,163
  • 5
  • 26
  • 55

1 Answers1

5

Firestore does not have an operation that allows you to update an existing item in an array by its index.

To update an existing item in the array, you will need to:

  1. Read the entire document into your application.
  2. Modify the item in the array in your application code.
  3. Write back the entire array to the document.

I'm pretty sure this has been asked before, so let me see if there's an answer with an example.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • What would be a more friendly way to deal with 'bookings' in my app? I'd still need them separated by date. I feel like I'm going to have trouble with arrays... – uber Jun 17 '20 at 14:30
  • 1
    I'd expect them to be in a subcollection, which is one way to solve the "three step problem" and also allows them to be queried. But that of course comes at a higher cost, since you'll need to read/write more documents. – Frank van Puffelen Jun 17 '20 at 15:36