Zaeem Khaliq
Zaeem Khaliq

Reputation: 316

How to update an array of Objects in Firebase Firestore?

I know how to update an array of objects like this:- (Note: This is the field in my Firestore DB)

details: [
{para:'Something..'},
{para:'Something again...'}
]

It will be done like this:-

db.collection(myCollection).doc(myID).update({
    details: firebase.firestore.FieldValue.arrayUnion({
        para: 'This will get added'
        })
    })

But What if the array of objects is inside another object like this??

details: {
    descrip: [
        {para:'Something..'}
    ]
}

When I try to do like this:-

db.collection(myCollection).doc(myID).update({
        details: {
            descrip: firebase.firestore.FieldValue.arrayUnion({
                para: 'This will get added'
            })
        }
        })

It removes the old para('Something..') and replaces it with the new one('This will get added').

I want this to happen:-

details: {
    descrip: [
        {para:'Something..'},
        {para:'This will get added'}
    ]
}

Is there any way to do it??

You may ask that if there is an easy way to do it(The above one) then why doing this. Actually this is just an example to get an idea of how it works. I am working on nested arrays of objects.

Upvotes: 0

Views: 91

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83191

The following should do the trick:

  db.collection('myCollection')
    .doc('myID')
    .update({
      ['details.descrip']: firebase.firestore.FieldValue.arrayUnion({
        para: 'This will get added',
      }),
    });

Upvotes: 1

Related Questions