scorval
scorval

Reputation: 57

Firestore Array of map not updating

So I'm working on a personal project to learn react-native and Firestore.

I have a DB like this:

Db image

And I want my code to add a new battery in the array batteries. The elements in the array are just a map{string, string}

The problem is that when I update the array with a new brand that's work but if I want to update it with the same brand again have, so having by the end

batteries[0]: {'brand': 'cestmoi'}
batteries[1]: {'brand': 'cestmoi'}

The DB doesn't update, doesn't have any error or so.

I don't understand why and I followed their tutorial. Here is my code:

async function addData(collection, doc, value) {
    console.log(`Add data ${value.brand}`)
    try {
        const result = await firestore()
                    .collection(collection)
                    .doc(doc)
                    .set({
                        batteries: firestore.FieldValue.arrayUnion(value)
                    })
        console.log(result);
        return result;
    } catch (error) {
        return error;
    }
}

I use try-catch by habit but I don't know if the then...catch is better or not.

Upvotes: 1

Views: 473

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138804

As already @windowsill mentioned in his answer, there is no way you can add duplicate elements in an array using client-side code. If your application requires that, then you have to read the entire array, add the duplicates and then write the document back to Firestore.

However, if you want to update an existing element in an array of objects (maps) then you have to use arrayUnion with the entire object. If you want to understand the mechanism better, you can read the following article which is called:

Upvotes: 2

windowsill
windowsill

Reputation: 3649

arrayUnion says that it "adds elements to an array but only elements not already present". Maybe it does a stringify or something to check equality and therefore doesn't add the new element. I think you'll have to 1. get the current list, 2. add your element, 3. set the batteries field to the updated list.

Upvotes: 1

Related Questions