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})
})
}
}
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With