Mgo即使不为空也忽略字段

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,

我想知道是否有某种方法可以使stuct字段即使提交也不提交给mgo 不是空的。 p>

我发现做到这一点的唯一方法是使字段变为小写,这使访问变得很麻烦。 还有另一种方法吗? p>

这是一个示例,我的目标是不将SSN提交到数据库中,但仍将其大写。 p>

 包main 
 
import(
“ fmt” 
“ crypto / sha1” 
“ encoding / base64” 
“ labix.org/v2/mgo” 
)
 
type Person结构 {
名称字符串
 SSN字符串
 HashedSSN字符串
} 
 
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:无法拨号到mgoSession”,err)
}否则{
 mgoSession.DB(“ test  “).C(” person“)。Insert(bob)
} 
} 
  code>  pre> 
 
 

谢谢 p> div>

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

type T struct {
    Field string `bson:"-"`
}