Search code examples
javascriptfirebasegoogle-cloud-firestore

How to update specific items in an array of objects is Firebase?


I have a doc in firebase representing a class in schoold, which has a list of object items including array of objects:

{{students: [{
          id: "xxx",
          name: "John",
          weight: "55",
          isPassed: false
        },
        {
          id: "xxx",
          name: "Marley",
          weight: "44",
          isPassed: false
        },
        {
          id: "xxx",
          name: "Beth",
          weight: "48",
          isPassed: false
        },
        {
          id: "xxx",
          name: "David",
          weight: "58",
          isPassed: true
        },
      ]
    },
teachers: {{...}},
name: "Tigers"
}

I am trying to update all items having isPassed key to true. I need something like:

await updateDoc(doc(db,"classes", class.id), { 
        "students.isPassed": true   // I know this syntax is wrong
      })

How is this possible?


Solution

  • To update all items having isPassed to true, you can change the isPassed inside a map function:

    const classRef = doc(db, "classes", class.id);
    const classSnapshot = await getDoc(classRef);
    
    if (classSnapshot.exists()) {
     const classData = classSnapshot.data();
     const updatedStudents = classData.students.map(student => {
      if (!student.isPassed) {
       return { ...student, isPassed: true };
      }
      return student;
    });
    
    await updateDoc(classRef, { students: updatedStudents });
    }