Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to update a specific index from the array in Firestore

Is there any way to update a specific index from the array in Firebase/firestore?

 export const editComment = (comment) => {
 return (dispatch, getState, { getFirebase, getFirestore }) => {
    const firestore = getFirestore();

    firestore.collection('topics').doc(comment.topicId).update({

     comments:  <--- this is array of objects


    }).then(() => {
      dispatch({ type: 'EDIT_COMMENT' })
    }).catch((error) => {
      dispatch({ type: 'EDIT_COMMENT_ERROR', error})
    })
  }
}
like image 474
Fhranis Holdt Avatar asked Jan 02 '19 09:01

Fhranis Holdt


People also ask

How do you update an array element in firestore?

When it comes to the official documentation regarding how to update elements in an array in Firestore, it says that: 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.

How do I update my firestore value?

Firestore Update Document Field What if we want to just update a value of a specific field in an existing document. To do that, all we have to do is add a third argument to the setDoc() method. It will be a JavaScript object with a single property: merge:true.

Are arrays indexed in firestore?

Automatic indexing For each map field, Cloud Firestore creates one collection-scope ascending index and one descending index for each non-array and non-map subfield in the map. For each array field in a document, Cloud Firestore creates and maintains a collection-scope array-contains index.


1 Answers

Is there any way to update a specific index from the array in Firestore?

No, there is not! This is not possible because if you want to perform an update, you need to know the index of that particular element. When talking about Cloud Firestore arrays, the things are different that you might think.

Because we are creating apps that can be used in a multi user environment, try to think what might happen if a user wants to edit a value at index 0, some other user wants to delete the value at index 0 and in the same time some other user might want to add another item at index 0. For sure, you'll end up having very different results and why not, get even array out of bounds exception. So Firestore actions with arrays are a little bit different. So you cannot perform actions like, insert, update or delete at a specific index.

If those two methods do not help you enough, you should get the entire document, get the array, modify it and add it back to the database.

like image 105
Alex Mamo Avatar answered Oct 11 '22 12:10

Alex Mamo