Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
141
rated 0 times [  143] [ 2]  / answers: 1 / hits: 18893  / 6 Years ago, wed, september 5, 2018, 12:00:00

I have a document in Firebase Firestore that is something like the below. The main point here is that I have an array called items with objects inside it:



{
name: 'Foo',
items: [
{
name: 'Bar',
meta: {
image: 'xyz.png',
description: 'hello world'
}
},
{
name: 'Rawr',
meta: {
image: 'abc.png',
description: 'hello tom'
}
}
]
}


I am trying to update a field inside the item array, under the meta object. For example items[0].meta.description from hello world to hello bar



Initially I attempted to do this:



  const key = `items.${this.state.index}.meta.description`
const property = `hello bar`;

this.design.update({
[key]: property
})
.then(() => {
console.log(done)
})
.catch(function(error) {
message.error(error.message);
});


This didn't appear to work though, as it removed everything in the item index I wanted to modify, and just kept the description under the meta object



I am now trying the following which basically rewrites the whole meta object with the new data



  const key = `items.${this.state.index}.meta`
const property = e.target.value;
let meta = this.state.meta;
meta[e.target.id] = property;

this.design.update({
[key]: meta
})
.then(() => {
this.setState({
[key]: meta
})
})
.catch(function(error) {
message.error(error.message);
});


Unfortunately though, this seems to turn my whole items array into an object that looks something like:



{
name: 'Foo',
items: {

0: {
name: 'Bar',
meta: {
image: 'xyz.png',
description: 'hello world'
}
},
1: {
name: 'Rawr',
meta: {
image: 'abc.png',
description: 'hello tom'
}
}
}
}


Any ideas how I can just update the content I want to?


More From » arrays

 Answers
30

Firestore doesn't have the ability to update an existing element in an indexed array. Your only array options for updates are described in the documentation - you can add a new element to the array (arrayUnion) or remove an element (arrayRemove).



As an alternative, you can read the entire array out of the document, make modifications to it in memory, then update the modified array field entirely.


[#53554] Sunday, September 2, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jenna

Total Points: 706
Total Questions: 107
Total Answers: 106

Location: Azerbaijan
Member since Tue, Sep 21, 2021
3 Years ago
;