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

Time:02-22

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

CodePudding user response:

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" }),
});
  • Related