Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mgo omit field even when not empty

Tags:

mongodb

go

mgo

I was wondering if there is any way to have a stuct field that doesn't get commited to mgo even if it isn't empty.

The only way I have found to do this is to make the field lowercase, which makes it a pain to access. Is there another way?

This is an example, and my goal here is to not commit the SSN into the database but still have it uppercase.

package main

import (
  "fmt"
    "crypto/sha1"
    "encoding/base64"
    "labix.org/v2/mgo"
)

type Person struct{
  Name string
  SSN string
  HashedSSN string
}

func main() {
  bob := Person{"Bob", "fake_ssn", ""}
  hasher := sha1.New()
  hasher.Write( []byte(bob.SSN))
  sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
  bob.HashedSSN = sha
  mgoSession, err := mgo.Dial("localhost:27017")
  if err != nil {
    fmt.Println("mongo_config#initMongoSessions : Could not dial to mgoSession", err)
  } else {
    mgoSession.DB("test").C("person").Insert(bob)
  }
}

Thanks,

like image 323
Gary Avatar asked Apr 03 '14 19:04

Gary


1 Answers

You can do that by using the field tag as follows:

type T struct {
    Field string `bson:"-"`
}
like image 187
Gustavo Niemeyer Avatar answered Sep 24 '22 19:09

Gustavo Niemeyer