简体   繁体   中英

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

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")
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM