This is my current Firestore in Firebase.
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?
Advertisement
Answer
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.
database.collection('users').doc(uid).update({ savedSearches: firebase.firestore.FieldValue.arrayUnion(data) });