Best Practices For Ignoring Nil Values in Firestore












0















I am building custom webservices using Golang (Go-Swagger for API Definition) and Firestore as my document store. Everything is working fine except it gets "awkward" on Updates to the database. I have a solution but I am not convinced it is the most elegant one. Has anyone else run into this, and how did they solve it....



Problem Statement: Nil values are overwriting existing values in firebase when I write to the database



Proposed Solution - MY API has json:"omitempty" on optional parameters and nil values will be passed in (as opposed to getting the default golang values). I am planning on taking the Struct passed into the API and one attr at a time populating it into my Struct that firestore is using. I have performance concerns but don't want to couple my API Struct with my DB Struct. I am also going to set the firestore:"omitempty"` string literal on my firestore struct much like the API Struct. I hope this will tell firestore to not write any values that are nil.



Is this the best way? Are their other alternatives? The default values of golang seems to have pluses and minuses.



UPDATE:



I ended up in a similar place as my proposed solution but also followed the suggestion that Dimitry suggested. I created an firestore.Update object to contain only the values that I want to update. When I called firestore it will only update those values.



Here is the function that I am using to call firestore.



func updateProfileUsingUpdateMethod(documentName string, values firestore.Update) error {
ctx := context.Background()
app := firestorehelper.GetFirestoreApp()

client, err := app.Firestore(ctx)
if err != nil {
return err
}
defer client.Close()

//Set the updated date

wr, error := client.Doc(collectionName+"/"+documentName).Update(ctx, values)
if error != nil {
return error
}
fmt.Println(wr.UpdateTime)
//Assume success
return nil
}


I also create a firestore.Update object and will append that to my firestore.Update slice.



firestore.Update{Path: "PATH_TO_ATTR", Value: VALUE_TO_PASS_IN}









share|improve this question





























    0















    I am building custom webservices using Golang (Go-Swagger for API Definition) and Firestore as my document store. Everything is working fine except it gets "awkward" on Updates to the database. I have a solution but I am not convinced it is the most elegant one. Has anyone else run into this, and how did they solve it....



    Problem Statement: Nil values are overwriting existing values in firebase when I write to the database



    Proposed Solution - MY API has json:"omitempty" on optional parameters and nil values will be passed in (as opposed to getting the default golang values). I am planning on taking the Struct passed into the API and one attr at a time populating it into my Struct that firestore is using. I have performance concerns but don't want to couple my API Struct with my DB Struct. I am also going to set the firestore:"omitempty"` string literal on my firestore struct much like the API Struct. I hope this will tell firestore to not write any values that are nil.



    Is this the best way? Are their other alternatives? The default values of golang seems to have pluses and minuses.



    UPDATE:



    I ended up in a similar place as my proposed solution but also followed the suggestion that Dimitry suggested. I created an firestore.Update object to contain only the values that I want to update. When I called firestore it will only update those values.



    Here is the function that I am using to call firestore.



    func updateProfileUsingUpdateMethod(documentName string, values firestore.Update) error {
    ctx := context.Background()
    app := firestorehelper.GetFirestoreApp()

    client, err := app.Firestore(ctx)
    if err != nil {
    return err
    }
    defer client.Close()

    //Set the updated date

    wr, error := client.Doc(collectionName+"/"+documentName).Update(ctx, values)
    if error != nil {
    return error
    }
    fmt.Println(wr.UpdateTime)
    //Assume success
    return nil
    }


    I also create a firestore.Update object and will append that to my firestore.Update slice.



    firestore.Update{Path: "PATH_TO_ATTR", Value: VALUE_TO_PASS_IN}









    share|improve this question



























      0












      0








      0








      I am building custom webservices using Golang (Go-Swagger for API Definition) and Firestore as my document store. Everything is working fine except it gets "awkward" on Updates to the database. I have a solution but I am not convinced it is the most elegant one. Has anyone else run into this, and how did they solve it....



      Problem Statement: Nil values are overwriting existing values in firebase when I write to the database



      Proposed Solution - MY API has json:"omitempty" on optional parameters and nil values will be passed in (as opposed to getting the default golang values). I am planning on taking the Struct passed into the API and one attr at a time populating it into my Struct that firestore is using. I have performance concerns but don't want to couple my API Struct with my DB Struct. I am also going to set the firestore:"omitempty"` string literal on my firestore struct much like the API Struct. I hope this will tell firestore to not write any values that are nil.



      Is this the best way? Are their other alternatives? The default values of golang seems to have pluses and minuses.



      UPDATE:



      I ended up in a similar place as my proposed solution but also followed the suggestion that Dimitry suggested. I created an firestore.Update object to contain only the values that I want to update. When I called firestore it will only update those values.



      Here is the function that I am using to call firestore.



      func updateProfileUsingUpdateMethod(documentName string, values firestore.Update) error {
      ctx := context.Background()
      app := firestorehelper.GetFirestoreApp()

      client, err := app.Firestore(ctx)
      if err != nil {
      return err
      }
      defer client.Close()

      //Set the updated date

      wr, error := client.Doc(collectionName+"/"+documentName).Update(ctx, values)
      if error != nil {
      return error
      }
      fmt.Println(wr.UpdateTime)
      //Assume success
      return nil
      }


      I also create a firestore.Update object and will append that to my firestore.Update slice.



      firestore.Update{Path: "PATH_TO_ATTR", Value: VALUE_TO_PASS_IN}









      share|improve this question
















      I am building custom webservices using Golang (Go-Swagger for API Definition) and Firestore as my document store. Everything is working fine except it gets "awkward" on Updates to the database. I have a solution but I am not convinced it is the most elegant one. Has anyone else run into this, and how did they solve it....



      Problem Statement: Nil values are overwriting existing values in firebase when I write to the database



      Proposed Solution - MY API has json:"omitempty" on optional parameters and nil values will be passed in (as opposed to getting the default golang values). I am planning on taking the Struct passed into the API and one attr at a time populating it into my Struct that firestore is using. I have performance concerns but don't want to couple my API Struct with my DB Struct. I am also going to set the firestore:"omitempty"` string literal on my firestore struct much like the API Struct. I hope this will tell firestore to not write any values that are nil.



      Is this the best way? Are their other alternatives? The default values of golang seems to have pluses and minuses.



      UPDATE:



      I ended up in a similar place as my proposed solution but also followed the suggestion that Dimitry suggested. I created an firestore.Update object to contain only the values that I want to update. When I called firestore it will only update those values.



      Here is the function that I am using to call firestore.



      func updateProfileUsingUpdateMethod(documentName string, values firestore.Update) error {
      ctx := context.Background()
      app := firestorehelper.GetFirestoreApp()

      client, err := app.Firestore(ctx)
      if err != nil {
      return err
      }
      defer client.Close()

      //Set the updated date

      wr, error := client.Doc(collectionName+"/"+documentName).Update(ctx, values)
      if error != nil {
      return error
      }
      fmt.Println(wr.UpdateTime)
      //Assume success
      return nil
      }


      I also create a firestore.Update object and will append that to my firestore.Update slice.



      firestore.Update{Path: "PATH_TO_ATTR", Value: VALUE_TO_PASS_IN}






      firebase go google-cloud-firestore






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 3 at 6:02







      mornindew

















      asked Jan 2 at 19:24









      mornindewmornindew

      5783721




      5783721
























          1 Answer
          1






          active

          oldest

          votes


















          0














          You have two options:




          1. Use map[string]interface{}


          2. Use custom structure with firestore attribute -firestore:"FieldName,omitempty".



            _, err := client.Collection("cities").Doc("DC").Set(ctx, map[string]interface{}{
            "capital": true,
            }, firestore.MergeAll)
            if err != nil {
            // Handle any errors in an appropriate way, such as returning them.
            log.Printf("An error has occurred: %s", err)
            }




          Do not confuse json omitempty with firestore.



          You also must to provide field name as this syntax will use omitempty as name.



          firestore:"omitempty" - not correct


          https://firebase.google.com/docs/firestore/manage-data/add-data



          code






          share|improve this answer


























          • Thank you. Even though you are saying to use the "update" Go API you appear to be using the "Set" call. I assume that wasn't a mistake? Just to make sure that I understand your suggestion.... Instead of marshalling over from my API struct to my firebase struct I should marshal over from my API Struct over to a map[string]interface{} but make sure that I don't marshal over any of the nil values that were passed into the API. Am I thinking straight?

            – mornindew
            Jan 2 at 21:31











          • You are right. Document comment confused me - use the update() method:

            – Dmitry Harnitski
            Jan 2 at 21:41












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54012064%2fbest-practices-for-ignoring-nil-values-in-firestore%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          You have two options:




          1. Use map[string]interface{}


          2. Use custom structure with firestore attribute -firestore:"FieldName,omitempty".



            _, err := client.Collection("cities").Doc("DC").Set(ctx, map[string]interface{}{
            "capital": true,
            }, firestore.MergeAll)
            if err != nil {
            // Handle any errors in an appropriate way, such as returning them.
            log.Printf("An error has occurred: %s", err)
            }




          Do not confuse json omitempty with firestore.



          You also must to provide field name as this syntax will use omitempty as name.



          firestore:"omitempty" - not correct


          https://firebase.google.com/docs/firestore/manage-data/add-data



          code






          share|improve this answer


























          • Thank you. Even though you are saying to use the "update" Go API you appear to be using the "Set" call. I assume that wasn't a mistake? Just to make sure that I understand your suggestion.... Instead of marshalling over from my API struct to my firebase struct I should marshal over from my API Struct over to a map[string]interface{} but make sure that I don't marshal over any of the nil values that were passed into the API. Am I thinking straight?

            – mornindew
            Jan 2 at 21:31











          • You are right. Document comment confused me - use the update() method:

            – Dmitry Harnitski
            Jan 2 at 21:41
















          0














          You have two options:




          1. Use map[string]interface{}


          2. Use custom structure with firestore attribute -firestore:"FieldName,omitempty".



            _, err := client.Collection("cities").Doc("DC").Set(ctx, map[string]interface{}{
            "capital": true,
            }, firestore.MergeAll)
            if err != nil {
            // Handle any errors in an appropriate way, such as returning them.
            log.Printf("An error has occurred: %s", err)
            }




          Do not confuse json omitempty with firestore.



          You also must to provide field name as this syntax will use omitempty as name.



          firestore:"omitempty" - not correct


          https://firebase.google.com/docs/firestore/manage-data/add-data



          code






          share|improve this answer


























          • Thank you. Even though you are saying to use the "update" Go API you appear to be using the "Set" call. I assume that wasn't a mistake? Just to make sure that I understand your suggestion.... Instead of marshalling over from my API struct to my firebase struct I should marshal over from my API Struct over to a map[string]interface{} but make sure that I don't marshal over any of the nil values that were passed into the API. Am I thinking straight?

            – mornindew
            Jan 2 at 21:31











          • You are right. Document comment confused me - use the update() method:

            – Dmitry Harnitski
            Jan 2 at 21:41














          0












          0








          0







          You have two options:




          1. Use map[string]interface{}


          2. Use custom structure with firestore attribute -firestore:"FieldName,omitempty".



            _, err := client.Collection("cities").Doc("DC").Set(ctx, map[string]interface{}{
            "capital": true,
            }, firestore.MergeAll)
            if err != nil {
            // Handle any errors in an appropriate way, such as returning them.
            log.Printf("An error has occurred: %s", err)
            }




          Do not confuse json omitempty with firestore.



          You also must to provide field name as this syntax will use omitempty as name.



          firestore:"omitempty" - not correct


          https://firebase.google.com/docs/firestore/manage-data/add-data



          code






          share|improve this answer















          You have two options:




          1. Use map[string]interface{}


          2. Use custom structure with firestore attribute -firestore:"FieldName,omitempty".



            _, err := client.Collection("cities").Doc("DC").Set(ctx, map[string]interface{}{
            "capital": true,
            }, firestore.MergeAll)
            if err != nil {
            // Handle any errors in an appropriate way, such as returning them.
            log.Printf("An error has occurred: %s", err)
            }




          Do not confuse json omitempty with firestore.



          You also must to provide field name as this syntax will use omitempty as name.



          firestore:"omitempty" - not correct


          https://firebase.google.com/docs/firestore/manage-data/add-data



          code







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 2 at 21:46

























          answered Jan 2 at 20:27









          Dmitry HarnitskiDmitry Harnitski

          3,86311834




          3,86311834













          • Thank you. Even though you are saying to use the "update" Go API you appear to be using the "Set" call. I assume that wasn't a mistake? Just to make sure that I understand your suggestion.... Instead of marshalling over from my API struct to my firebase struct I should marshal over from my API Struct over to a map[string]interface{} but make sure that I don't marshal over any of the nil values that were passed into the API. Am I thinking straight?

            – mornindew
            Jan 2 at 21:31











          • You are right. Document comment confused me - use the update() method:

            – Dmitry Harnitski
            Jan 2 at 21:41



















          • Thank you. Even though you are saying to use the "update" Go API you appear to be using the "Set" call. I assume that wasn't a mistake? Just to make sure that I understand your suggestion.... Instead of marshalling over from my API struct to my firebase struct I should marshal over from my API Struct over to a map[string]interface{} but make sure that I don't marshal over any of the nil values that were passed into the API. Am I thinking straight?

            – mornindew
            Jan 2 at 21:31











          • You are right. Document comment confused me - use the update() method:

            – Dmitry Harnitski
            Jan 2 at 21:41

















          Thank you. Even though you are saying to use the "update" Go API you appear to be using the "Set" call. I assume that wasn't a mistake? Just to make sure that I understand your suggestion.... Instead of marshalling over from my API struct to my firebase struct I should marshal over from my API Struct over to a map[string]interface{} but make sure that I don't marshal over any of the nil values that were passed into the API. Am I thinking straight?

          – mornindew
          Jan 2 at 21:31





          Thank you. Even though you are saying to use the "update" Go API you appear to be using the "Set" call. I assume that wasn't a mistake? Just to make sure that I understand your suggestion.... Instead of marshalling over from my API struct to my firebase struct I should marshal over from my API Struct over to a map[string]interface{} but make sure that I don't marshal over any of the nil values that were passed into the API. Am I thinking straight?

          – mornindew
          Jan 2 at 21:31













          You are right. Document comment confused me - use the update() method:

          – Dmitry Harnitski
          Jan 2 at 21:41





          You are right. Document comment confused me - use the update() method:

          – Dmitry Harnitski
          Jan 2 at 21:41




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54012064%2fbest-practices-for-ignoring-nil-values-in-firestore%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          MongoDB - Not Authorized To Execute Command

          Npm cannot find a required file even through it is in the searched directory

          in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith