首页 > 解决方案 > 如何增加地图字段中的值?

问题描述

我有一个更新firestore中数据的功能

  setLocalStorage = name => () => {
    ...

    this.database.collection(this.cookie.get('section')).doc(this.cookie.get('id')).update({
      ['daily.' + name]: this.database.FieldValue.increment(1),
      ['monthly.' + name]: this.database.FieldValue.increment(1),
      ['yearly.' + name]: this.database.FieldValue.increment(1)
    })
  }

在此处输入图像描述

我想在作为对象映射的字段中增加我的值,但这种方法不起作用。我该怎么做?

标签: javascriptreactjsfirebasegoogle-cloud-firestore

解决方案


好的,所以我找到了一个解决方案(我不知道它是否可以,但它可以工作)。首先,我使用正确的键创建新对象,接下来我从 firestore 获取值,将它们递增并归属于之前创建的对象键,然后我使用之前归属的递增值更新 firestore 中的值。

    let incrementObj = {
      daily: 0,
      monthly: 0,
      yearly: 0,
    };
    await this.database
      .collection(this.cookie.get("section"))
      .doc(this.cookie.get("id"))
      .get()
      .then((snapshot) => {
        let dailyValue = snapshot.data().daily[name] + 1;
        let monthlyValue = snapshot.data().monthly[name] + 1;
        let yearlyValue = snapshot.data().yearly[name] + 1;
        incrementObj.daily = dailyValue;
        incrementObj.monthly = monthlyValue;
        incrementObj.yearly = yearlyValue;
      });

    await this.database
      .collection(this.cookie.get("section"))
      .doc(this.cookie.get("id"))
      .update({
        ["daily." + name]: incrementObj.daily,
        ["monthly." + name]: incrementObj.monthly,
        ["yearly." + name]: incrementObj.yearly,
      });

推荐阅读