首页 > 解决方案 > 如何使用 firebase 增量功能?

问题描述

我正在寻找一种方法,当任何文档添加到 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。我希望随着新数据的添加而增加一些东西

标签: javascriptfirebasereact-nativegoogle-cloud-firestore

解决方案


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

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

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


推荐阅读