Home > Mobile >  How can I add objects to an array of Objects which has same keys in firestore?
How can I add objects to an array of Objects which has same keys in firestore?

Time:10-12

I have a Collection called Notes which has a document that is an UID of the user that consists of collection of an Array of objects which look something like this

obj {[
 {title:"Note 1",desc:"description 1"},
 {title:"Note 2",desc:"description 2"},
 {title:"Note 3",desc:"description 3"},
]}

this is the actual Firestore collection where is now allowing me to store objects with the same key using the code I wrote but If I'm trying to add it manually then I

enter image description here I'm using react with firebase and using Firestore as a database

the problem I'm facing is that if I add more objects to the array mentioned above with the same key it's not creating a duplicate Firestore is not letting me add more objects with the same key. Other than that it is running just fine.

Below is the code for adding a new Notes Collection

// this function create a new Notes Collection
const createNotes = async (title, description) => {
  const uid = auth.currentUser.uid; // For document name
  const notesRef = doc(db, "Notes", uid);
  const data = {
    note: [{ title: title, description: description }],
  };
    try {
    await setDoc(notesRef, data);
  } catch (error) {
    console.log(error);
  }
};

Below is the code for updating the array of objects, this was the only way I could find to add multiple objects into an array on firestore

const updateNotes = async (title, description) => {
  const uid = auth.currentUser.uid;
  const notesRef = doc(db, "Notes", uid);
  const data = {
    note: arrayUnion({ title: title, description: description }),
  };
  try {
    await updateDoc(notesRef, data, { merge: true });
  } catch (error) {
    console.log(error);
  }
};

Is there a solution to this?

CodePudding user response:

According to your last comment:

If suppose I have added an array field such as {title:”a”,desc:”b”} in the array and if again try to add the same object it will not create a duplicate of the same object how will I be able to have multiple same objects in an array?

Please note that you cannot add duplicate elements in an array using arrayUnion. According to the official documentation:

arrayUnion() adds elements to an array but only elements not already present.

So if you need to have duplicate elements, then the single option that you is to read the document, add the duplicate element in the array, and then write the document back to Firestore.

  • Related