Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to add a new key and value to an existing object in firebase 9 without overwriting previous data

I am trying to add to an object in firestore, the problem is the new object overwrites the previous objects so in my case only one object remains, i put a picture of the db and also the logic that I am using.

      const docRef = doc(db, 'items', _authContext.currentUser.uid);

      await updateDoc(docRef, {
        itemlist: {
          [diffrent key each time]:  arrayUnion({ name: 'item whatever')}],
        },
      }), { merge: true };
    };

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should use dot notation when updating a nested field. Also updateDoc() doesn’t take the options with merge property (it’s setDoc() that does). Try refactoring the code as shown below:

const docRef = doc(db, 'items', _authContext.currentUser.uid);
const differentKey = "someKey";

await updateDoc(docRef, {
  [`itemList.${differentKey}`]: arrayUnion({ name: "item whatever" }),
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading