Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

79
Vistas
Firebase updating the retrieved data

I was practicing firebase firestore and I am trying to update the data I retrieved based on a condition and I am getting this error

FirebaseError: Expected type 'rc', but it was: a custom oc object

 if (updateMerge === "update") {
  const q = query(
    collection(db, "contacts"),
    where("fname", "==", firstName, "lname", "==", lastName)
  );
  const querySnapshot = await getDocs(q);
  querySnapshot.forEach((doc) => {
    console.log(doc.id, " => ", doc.data());
    const payload = { phone: phone };
    setDoc(q, payload);
  });
}

I am doing a contact app I can see the retrieved data on the console and I want to change the phone number if a user already has an account, so the payload changes the phone(from firestore document field):phone(phone state). so I have done some practice with setDoc but I usually use "collectionRef" but not with a query, if I can see the console most probably the error would be here

setDoc(q, payload);

Thanks In advance

7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The setDoc() takes a DocumentReference as first parameter. If you are trying to update the documents in the QuerySnapshot, try refactoring the code as shown below:

querySnapshot.forEach((doc) => {
  console.log(doc.id, " => ", doc.data());
  const payload = { phone: phone };

  // doc.ref is DocumentReference
  setDoc(doc.ref, payload);
});

If you are updating 500 or less documents, then you can use Batched Writes to ensure all documents are either updated or the update fails:

import { writeBatch } from "firebase/firestore"; 

const batch = writeBatch(db);

querySnapshot.forEach((doc) => {
  console.log(doc.id, " => ", doc.data());
  const payload = { phone: phone };

  // doc.ref is DocumentReference
  batch.update(doc.ref, payload);
});

batch.commit().then(() => {
  console.log("Documents updated")
}).catch((e) => {
  console.log("An error occured")
})
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos