10

我想知道是否有任何方法可以让 stuct 字段即使不为空也不会提交给 mgo。

我发现这样做的唯一方法是将字段设为小写,这使得访问变得很痛苦。还有其他方法吗?

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

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)
  }
}

谢谢,

4

1 回答 1

29

您可以通过使用 field 标签来做到这一点,如下所示:

type T struct {
    Field string `bson:"-"`
}
于 2014-04-03T19:40:29.497 回答