Search code examples
javascriptgoogle-cloud-firestoreangularfire2

how do I push an object to a firestore array?


I have a Firestore array called ActivityLogList[]. There will be other users editing their objects concurrently in this Array (each user will have their own object). What I am attempting is to add/edit this object without modifying the other users objects. Previously I have downloaded the complete array and then editing my object and then updateDoc.

Firebase console

enter image description here

each of these ActivityLogList objects has there own this.auth.currentUser?.uid which is why I do not want to grab to whole ActivityLogList Array and add/edit as per the code below

ts

addToArray(array: any, object: any, eventid: any) {
  // array = ActivityLogList collection
  // object = object iserted into ActivityLogList collection
  array.push(object); // add the object to the array
  const ref = doc(this.firestore, `events/${eventid}`);
  //  ref = events in start collection
  return updateDoc(ref, { ActivityLogList: array });
}

The trouble with this is I could overwrite other users objects if they are editing their objects at the same time as myself. Is there a way I add/edit into the Array without grabbing the whole ActivityLogListArray?


Solution

  • You can add an item to an array field with an arrayUnion and remove specific items from an array with arrayRemove. Both of these are possible without reading the entire array.

    But there is no way to edit an item in an array without reading the entire array. The only way to edit an item is to:

    1. Read the document with the existing value
    2. In your application code modify the array
    3. Write the entire array field back to the database

    If you want to prevent reading/writing the entire array, consider if you should store the ActivityLogList a a subcollection rather than an array field. While that will require you to read/write more documents, it allows you to manipulate each document separate.