1

I have the below code which at first run creates a new collection with a document ID that is equal to my UID. This newly created document has an array named 'array' which contains the cocktailInformation object. So far all works fine.

const saveData = (uid) => {
        db
            .collection('users')
            .doc(uid)
            .set({
                array: [ cocktailInformation ]
            })
            .then(function() {
                console.log('Document successfully written!');
            })
            .catch(function(error) {
                console.error('Error writing document: ', error);
            });
    };

the issue arises when i want to add more objects to this array in this document. I checked firestore docs on how to do this and it shows the below

var washingtonRef = db.collection("cities").doc("DC");

// Atomically add a new region to the "regions" array field.
washingtonRef.update({
    regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")
});

// Atomically remove a region from the "regions" array field.
washingtonRef.update({
    regions: firebase.firestore.FieldValue.arrayRemove("east_coast")
});

but i don't know how to integrate this as the current code only updates the current object with the one i send off to firestore. Can anyone give me some tips? BTW this is a react app

2
  • How exactly do you define db in your code? Commented Apr 27, 2020 at 15:42
  • hey @DougStevenson I got this fixed thanks to stackoverflow.com/a/61460221/12998811 Commented Apr 27, 2020 at 15:45

1 Answer 1

4

You can update the document by doing the following:

db.collection('users').doc(uid).update({
    array: firebase.firestore.FieldValue.arrayUnion("value")
});
Sign up to request clarification or add additional context in comments.

6 Comments

Tried this mate. It gives me a Cannot read property 'arrayUnion' of undefined error when run
where are u calling this? in the browser or cloud functions?
I am calling this in the react component from which I want to add the new data to the array
also which version of firestore are u using?
I added the version and some other info you might find relevant to the issue here mate- codepile.net/pile/qDpgNnEV
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.