0

im trying to insert an object in an array in firestore but when the array already contains an object it just rewrite it and i only get 1 object everytime.

here is my code

const obj=[{
    name:xxx,
    age:28
}];

await dataBase.set({infos:obj},{merge:true})

Here is what I'm trying to do.

FiddlingAway
  • 1,598
  • 3
  • 14
  • 30
  • Your image seems to be showing an object which contains an array of objects. That is to say, something [like this](https://i.imgur.com/tGfuMdB.png). Is that what you want? Can you post your code, so we can get a better idea on what's going wrong? – FiddlingAway Jan 22 '23 at 16:33
  • @FiddlingAway yes that is what i want, yeah my bad i forgot to post the code, i will update the question. – Soufian Zanouti Jan 22 '23 at 16:34
  • @FiddlingAway here is my code :const obj=[{ name:xxx, age:28 }] await dataBase.set({infos:obj},{merge:true}) – Soufian Zanouti Jan 22 '23 at 16:37
  • Take a look at [this SO answer](https://stackoverflow.com/a/51794212/), it might help. Be sure to check the rest of them as well. – FiddlingAway Jan 22 '23 at 16:41

1 Answers1

0

To add an object to an array that already contains objects in Firestore without rewriting the entire array, you can use the arrayUnion() or arrayRemove() method.

Here is an example of using arrayUnion() to add an object to an array:

// Add a new object to the 'items' array
firestore.collection("collectionName").doc("docId").update({
items: firebase.firestore.FieldValue.arrayUnion({ name: "itemName", 
quantity: 2 })
});