0

does anyone know how to push data to array in firebase without overwriting? I use this solution, but unfortunately it overwrites the existing data:

    db.collection('Goals').doc('Aqd8aP8uLSvuAgsMs5aW').update({"nested": ['12','14']})
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
jkovakuis
  • 35
  • 3

4 Answers4

1

If the items in the array are unique, you can use array union:

db.collection('Goals').doc('Aqd8aP8uLSvuAgsMs5aW')
  .update({"nested": firebase.firestore.FieldValue.arrayUnion(['12','14'])})

If the items in the array are not unique, there is no way to do this with a single statement, and you will need to:

  1. Read the document to get the array's current values.
  2. Add the new values to the array in your application code.
  3. Write the entire back to the document.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

According to the documentation https://firebase.google.com/docs/firestore/manage-data/add-data you should merge data:

If the document does not exist, it will be created. If the document does exist, its contents will be overwritten with the newly provided data, unless you specify that the data should be merged into the existing document, as follows:

  db.collection('Goals').doc('Aqd8aP8uLSvuAgsMs5aW').set({"nested": ['12','14']}, { merge: true });

0

You can use the Following syntax to solve the query

const handleOnSubmit = () =>{
    const dataRef = db.database().ref(user['']); 
    const data = ({
      *//data to push after every submit*

    });
    dataRef.push(data)
}
0

Possible it not best solution, but you can get current array and add new element.

    const { nested } = await db.collection('Goals').doc('id');

    nested.push('new element');

    await db.collection('Goals').doc('id').update( { nested } );
HardCoreQual
  • 331
  • 1
  • 3
  • 11