I am building a Next JS app with Firebase as the backend and I am using Firebase cloud functions to update certain Firestore fields. I use an onCreate trigger that carries the numbers by which I increment with.
The data looks something like this:
{
"docId": "a4wwdslidinwle",
"metaData": [
{
"data": "age",
"count": 1
},
{
"data": "skill",
"count": 3
}
],
"phoneNumber": "0800182712",
"uid": "j10wmCUhUWPxYJpIElBxmFAEI6l1"
}
and I increment the fields like this:
// INCREMENT FIRESTORE FIELD VALUE
var userData = admin.firestore().collection("user")
.doc(data.uid).update({
age: admin.firestore.FieldValue.increment(dataObject.age),
skill: admin.firestore.FieldValue.increment(dataObject.skill),
starRating: admin.firestore.FieldValue.increment(dataObject.starRating)
})
My challenge is, when the document is created and it doesn’t have the starRating
item, the cloud function throws an error that says the FieldValue.increment()
did not have a valid number. It works fine when the star Rating is set to a value.
Is there a way to increment by 0 if that value is missing from the document?
Please help. Thanks.
2
Answers
If I correctly understand your question, you can simply check for the existence of the field as follows:
The
increment
operator can safely be called with a value of0
, so: