【问题标题】:Increment counter firestore vue增量计数器 Firestore vue
【发布时间】:2018-06-04 16:27:16
【问题描述】:

我的 firebase 中有一个属性,在添加注册时需要增加该属性。添加注册有效,但我似乎无法弄清楚,当注册发生时,如何动态增加数量。 我的初始代码是:

countExperience() {
  db
    .collection("experiences")
    .doc(this.$route.params.experience_id)
    .update({ quantity: + 1 })
    .then(docRef => {
      console.log("added quantity");
    });
},

我的问题是“更新”不起作用,它基本上将值设置为 1,而不是递增它。

这是工作代码:

countExperience() {
  const exp_ref = db.collection("experiences").doc(this.$route.params.experience_id)

  return db.runTransaction(t => {
    return t.get(exp_ref).then(doc => {
      const newCount = doc.data().quantity +1
      t.update(exp_ref, {quantity: newCount})
    })
  })
},

【问题讨论】:

    标签: javascript firebase vue.js google-cloud-firestore


    【解决方案1】:

    您需要从文档中读取quantity 的值,将其递增,然后将其写回。您现在拥有的只是将值写入文档中,而无需先读取它。

    您通常希望use a transaction 执行此操作,以便这一切都以事务方式发生。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    相关资源
    最近更新 更多