【问题标题】:How search in mongo with using custom structure?如何使用自定义结构在 mongo 中搜索?
【发布时间】:2017-12-18 21:14:19
【问题描述】:

如何忽略查询中time字段的默认值?
因为设置在0001-01-01 00:00:00 +0000 UTC,所以找不到合适的文档

// User model
type User struct {
    Mail      string        `json:"mail" bson:"mail,omitempty"`
    Password  string        `json:"password" bson:"password,omitempty"`
    CreatedAt time.Time     `json:"created_at" bson:"created_at,omitempty"`
    UpdatedAt time.Time     `json:"updated_at" bson:"updated_at,omitempty"`
}

例如https://play.golang.org/p/P2P30PPtl0

【问题讨论】:

    标签: mongodb go struct default-value


    【解决方案1】:

    time.Time是一个struct类型,它的zero值是一个有效的时间值,不被认为是“空的”。因此,对于time.Time,如果您需要区分zero 和空值,请改用指向它的指针,即*time.Timenil 指针值将是 empty 值,任何非nil 指针值将表示非空时间值。

    type User struct {
        Mail      string     `json:"mail" bson:"mail,omitempty"`
        Password  string     `json:"password" bson:"password,omitempty"`
        CreatedAt *time.Time `json:"created_at" bson:"created_at,omitempty"`
        UpdatedAt *time.Time `json:"updated_at" bson:"updated_at,omitempty"`
    }
    

    查看相关问题:Golang JSON omitempty With time.Time Field

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 2012-04-09
      相关资源
      最近更新 更多