Home > database >  Can't update firebase collection field - Expected type 'ya', but it was: a custom Ia
Can't update firebase collection field - Expected type 'ya', but it was: a custom Ia

Time:01-11

I am trying to make barbershop web app where costumer can see list of free appointments and when they reserve free appointment I want to delete that field from firebase.

I have a collection which represents one barber. This is how it looks in firebase.

As you see radno_vrijeme is object or map in firebase which contains 6 arrays, and in each array there is list of free working hours.

In my function I am able to do everthing except last line where I need to update firebase collection.

  const finishReservation = async () => {
    try {
      const freeTimeRef = collection(db, `${barber}`);
      const q = query(freeTimeRef);
      const querySnap = await getDoc(q);
      querySnap.forEach(async (doc) => {
        const radnoVrijeme = doc.data().radno_vrijeme;

        // Find the index of the hour you want to delete
        const index = radnoVrijeme["Mon"].indexOf(hour);
        // Remove the hour from the array
        radnoVrijeme["Mon"].splice(index, 1);
        // Update the document in the collection
        console.log(radnoVrijeme);
        const radnoVrijemeMap = new Map(Object.entries(radnoVrijeme));
        await freeTimeRef.update({ radno_vrijeme: radnoVrijemeMap });
      });
    } catch (error) {
      console.log(error);
    }
  };

I tried to pass it as JSON stringified object, but it didn't work. I always get this error :

"FirebaseError: Expected type 'ya', but it was: a custom Ia object"

CodePudding user response:

When you are trying to fetch multiple documents using a collection reference or query, then you must use getDocs():

const finishReservation = async () => {
  try {
    const freeTimeRef = collection(db, `${barber}`);
    const q = query(freeTimeRef);
    const querySnap = await getDocs(q);
    
    const updates = [];
    
    querySnap.forEach((d) => {
      const radnoVrijeme = d.data().radno_vrijeme;    
      const index = radnoVrijeme["Mon"].indexOf(hour);
      radnoVrijeme["Mon"].splice(index, 1);
    
      const radnoVrijemeMap = new Map(Object.entries(radnoVrijeme));
      
      updates.push(updateDoc(d.ref, { radno_vrijeme: radnoVrijemeMap }))
    });
    
    await Promise.all(updates);
    console.log("Documents updated")
  } catch (error) {
    console.log(error);
  }
};

getDoc() is used to fetch a single document using a document reference.

  • Related