忽略字段即使不为空

huangapple go评论81阅读模式
英文:

Mgo omit field even when not empty

问题

我想知道是否有办法使一个结构字段即使为空也不会被提交到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)
    }
}

谢谢,

英文:

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,

答案1

得分: 31

你可以通过以下方式使用字段标签来实现:

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

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

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

huangapple
  • 本文由 发表于 2014年4月4日 03:15:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/22846879.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定