【问题标题】:How to update field in firebase document?如何更新firebase文档中的字段?
【发布时间】:2021-12-19 23:07:28
【问题描述】:

您好,我想更新 firebase 文档中的字段。

现在,我正在像这样访问文档集合 但是,我无法将文档的 share 字段设置为 share+=1 ? 我在 set 方法中做错了什么?

const buyStock = async () => {
const q = await query(
  collection(db, 'myStocks'),
  where('ticker', '==', props.name)
);
const querySnapshot = await getDocs(q);
if (!querySnapshot.empty) {
  // simply update the record

  querySnapshot.forEach((doc) => {
    doc.id.set({
      shares: doc.id.data().shares+=1
    })
    // doc.data() is never undefined for query doc snapshots
    console.log(doc, doc.id, ' => ', doc.data());
  });

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    你快到了。要更新文档,您需要对该文档的引用。您可以通过以下方式获得:

    querySnapshot.forEach((doc) => {
      doc.ref.update({
        shares: doc.data().shares+=1
      })
    });
    

    你也可以使用内置的atomic increment operator

    doc.ref.update({
      shares: increment(1)
    })
    

    【讨论】:

    • 我收到一个错误 doc.ref.update() is not a function?
    • 啊,是的,那可能是updateDoc(doc.ref, ...)。但在这种情况下,你的 doc.id.set() 应该会出现类似的错误。
    【解决方案2】:

    看起来您正在调用“id”字段的 set 方法。尝试删除它。所以就做吧

    doc.set({
      shares: doc.data().shares+=1
    })
    

    试一试。如果这不起作用,我会尝试更新不属于查询快照的文档。

    【讨论】:

    • 我得到一个错误 doc.set is not a function?
    猜你喜欢
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 2022-11-25
    • 2015-04-12
    相关资源
    最近更新 更多