How to add data to a nested object in Firestore

Tags: , ,

This is my current Firestore in Firebase. enter image description here

I need help adding data to the savedSearches map.

I need to use .set() (because a users savedSearches might not exist).

My current attempt looks like this:

database.collection('users').doc(uid).set({savedSearches: data}, {merge: true})

But this doesn’t add an object within savedSearches with a unique ID.

When I was using Firebase Realtime Database I was just doing this:

database.ref('users/' + uid + '/savedSearches').push(data)

And that worked perfectly. How can I do that in Firestore?


If your document contains an array field, you can use arrayUnion() and arrayRemove() to add and remove elements. arrayUnion() adds elements to an array but only elements not already present. arrayRemove() removes all instances of each given element.

    savedSearches: firebase.firestore.FieldValue.arrayUnion(data)

Source: stackoverflow