Home > Net >  How can i add new indexes to an array in an existing document in Firebase Firestore?
How can i add new indexes to an array in an existing document in Firebase Firestore?

Time:10-27

Good morning, I am working on building out a portion of an app where a user can add team members. Working with the set function created the array I wanted in firestore, but I'm unable to add new indexes to that array with more teams. The user should be able to add as many as they like. After doing some searching I thought the arrayUnion option in the update function would help my needs, but when I add more data from the form, the data in index [0] just gets overwritten rather than populating index ['1']. Below are some images that will illustrate my problem. enter image description here Here is the code that returns the results so far enter image description here

The document id is the users uid and I'd like to keep it that way to query all teams associated with that user, How can I add new indexes to an existing array with the same documentid of the current user? If an array isnt feasible here, I also tried to get the result I wanted with an object and that wasn't updating the way I needed it to either.

CodePudding user response:

Ok so, I would suggest to change the approach to have a collection inside each user document instead of an array. Some benefits would be that you're not limited to the 1mb limit that a document can have, but also that queries are more robust for collections.

To add a new team member you would use the .add() method, and for querying you have a lot more built in options. query documentation

Here is another so topic on the differences between using a subcollection or an array

EDIT

for your original question, the problem is that in Firestore, your array is an array of maps (objects), but you're calling arrayUnion with the individual fields. consider something like this:

db.collection("Teams").doc(uuid).update({
    team: firebase.firestore.FieldValue.arrayUnion(
              this.team  // object { selected: true, firstName: "abc", ... }
          )
})
  • Related