1

i've been googling around about how to add an object into an array in firestore, and found the arrayUnion() able to add an object into firestore array, but it only add the object into last index of array, but how to add it into first index of array?

//add "greater_virginia" into last index of array
washingtonRef.update({
    regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")
});

//how to add "greater_virginia" into first index of array?

its basically same as arrayUnion but instead of add it into last index, i want to add it into first index of array.

2 Answers 2

2

If Firestore arrays behave anything like realtime-database arrays, then they don't actually exist. As far as I know, they are store as maps, like:

{
  0: "first element",
  2: "second and so on",
}

You can probably see how an unshift would be a big transformation. In fact, firestore doesn't let you do this, saying "...in order to avoid some of the issues that can arise in a multi-user environment, you'll be adding them with more of a set-like functionality".

With that in mind, this problem is usually solved at the application level by fetching the array, mutating it as needed, then setting the whole thing.

Bit of further reading https://firebase.googleblog.com/2018/08/better-arrays-in-cloud-firestore.html

PS: be careful with the arrayUnion operator, because it actually performs a add to set

Sign up to request clarification or add additional context in comments.

4 Comments

Firestore array fields definitely do exist. They have their own dedicated field type that are different than maps. It's not like Realitme Database at all.
thank you for the answer very clear answer, do you know any syntax that i can use to fetch it manually, unshift it then push it into firestore? maybe i can do more research on it
Thanks for the clarification @DougStevenson. As for how to get and set data from your database, you'll have to read the beginning of the docs firebase.google.com/docs/firestore/query-data/get-data
Conceptually though it will be something like doc = get doc from collection; newArray = [newElement, ...doc.arrayField]; set newArray on arrayField of doc;
2

Firestore doesn't offer any way to modify items of array fields by index. arrayUnion will only ever append to the end of the array if the element doesn't already exist.

If you want to modify an array by index, you will have to read the document, modify the array in memory to appear how you want, then write the modified array back to the document.

2 Comments

Note: Unlike arrayUnion, this will fail atomicity
@AlbertRenshaw You can use a transaction for that.

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.