5

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?

1 Answer 1

4

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)
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This somehow works even when savedSearches isn't already defined, which I thought weren't possible with .update()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.