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']})

4 Answers 4

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:

Sign up to request clarification or add additional context in comments.

Comments

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 });

Comments

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)
}

Comments

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 } );

Comments

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.