2017-12-18 244 views
2

如何忽略查詢中time字段的默認值?
因爲他們在0001-01-01 00:00:00 +0000 UTC設置,我無法找到合適的文檔如何使用自定義結構在mongo中搜索?

// 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

回答

3

time.Time是一個結構類型,其zero值是一個有效時間值,不被視爲「空」。因此,如果您需要區分zero和空值,請使用指向它的指針time.Time,即*time.Timenil指針值將是空值值,並且任何非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

相關問題