简体   繁体   English

Firebase 更新检索到的数据

[英]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我正在练习 firebase firestore,我正在尝试根据条件更新我检索到的数据,但出现此错误

FirebaseError: Expected type 'rc', but it was: a custom oc object FirebaseError:预期类型为“rc”,但它是:自定义 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).我正在做一个联系人应用程序,我可以在控制台上看到检索到的数据,如果用户已经有一个帐户,我想更改电话号码,因此有效负载会更改电话(来自 firestore 文档字段):电话(电话状态)。 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 做了一些练习,但我通常使用“collectionRef”而不是查询,如果我能看到控制台,很可能错误会在这里

setDoc(q, payload);

Thanks In advance提前致谢

The setDoc() takes a DocumentReference as first parameter. setDoc()DocumentReference作为第一个参数。 If you are trying to update the documents in the QuerySnapshot , try refactoring the code as shown below:如果您尝试更新QuerySnapshot中的文档,请尝试重构代码,如下所示:

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:如果您要更新 500 个或更少的文档,则可以使用Batched Writes来确保所有文档都已更新或更新失败:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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