【问题标题】:How can I use firebase increment function?如何使用 firebase 增量功能?
【发布时间】:2019-11-23 17:51:07
【问题描述】:

我正在寻找一种方法,当任何文档添加到 firestore 集合中时,它会增加文档中的键。

我的代码:

firestore().collection('booking').add({
    bookingTime: bookingDate,
    userId: firebase.auth().currentUser.uid,
    timeslotId: selectedTimeSlot.timeslotId,
    bookingId: getBookingId(),
    appoitmentTime : selectedTimeSlot.displatString,
    age : info.age,
    gender : info.gender,
    name : info.name,
    phonenumber : info.phonenumber,


  })
    .then(docRef => {
      console.log("Document written with ID: ", docRef.id);
      firestore().collection('booking').doc(docRef.id).update({numberOfAppoitment: firebase.firestore.FieldValue.increment(1)});

    })
    .catch(error => {
      console.error("Error adding document: ", error);
    })

当前在numberOfAppoitment,它只添加 1。我希望随着新数据的添加而增加一些东西

【问题讨论】:

  • 我不明白你想在这里做什么。为什么不在添加文档的同时设置 numberOfAppoitment 以及所有其他字段?为什么需要稍后设置?
  • 是的,我可以做到。但我的问题是我希望该字段自动递增同时添加或添加后添加
  • 也许这个文档 -> googleapis.dev/nodejs/firestore/latest/… 或者这个教程 -> fireship.io/snippets/firestore-increment-tips 可以帮助你获得想要的行为。在这个问题上您还需要帮助吗?

标签: javascript firebase react-native google-cloud-firestore


【解决方案1】:

我认为您不能在更新时增加没有整数值的字段。如果您想稍后使用FieldValue.increment(),则应使用初始值 0 填充该字段。

firestore().collection('booking').add({
    numberOfAppoitment: 0,
    // include the other fields here...
})

您可能还想将该字段的拼写正确地视为“nubmerOfAppointment”。

【讨论】:

  • 您好,感谢您的回复。但如果集合中添加了 3 个文档,则不可能。然后我添加带有增量字段的新文档,它在该文档中添加 4 个值
猜你喜欢
  • 2021-09-15
  • 2018-01-01
  • 1970-01-01
  • 2016-09-15
  • 2019-09-09
  • 2020-05-09
  • 2018-02-17
  • 2018-06-10
  • 1970-01-01
相关资源
最近更新 更多