skip to Main Content

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


  1. If I correctly understand your question, you can simply check for the existence of the field as follows:

    const updateObject = {
        age: admin.firestore.FieldValue.increment(dataObject.age),
        skill: admin.firestore.FieldValue.increment(dataObject.skill),
    }
    if (dataObject.starRating) {
       updateObject.starRating =  admin.firestore.FieldValue.increment(dataObject.starRating)
    } else {
       updateObject.starRating = 0;
    }
    admin.firestore().collection("user").doc(data.uid).update(updateObject);
    
    Login or Signup to reply.
  2. The increment operator can safely be called with a value of 0, so:

    starRating: admin.firestore.FieldValue.increment(
      dataObject.starRating ? dataObject.starRating : 0
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search