简体   繁体   中英

How can I increment values in map fields?

I have a function for updating data in 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)
    })
  }

在此处输入图像描述

I want to increment my values in fields which are an object maps but this method isnt working. How can I do it differently?

Ok, so I found a solution (i dont know if its ok but it works). First of all I create new object with proper keys, next I get values from firestore, increment them and ascribe to before created object keys and next I update values in firestore with before ascribed incremented values.

    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,
      });

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