如何使用自定义结构在mongo中搜索?

问题描述 投票:2回答:1

如何忽略查询中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个回答
4
投票

time.Time是一种结构类型,其zero值是一个有效的时间值,不被视为“空”。所以在time.Time的情况下,如果你需要区分zero和空值,请使用指向它的指针,即*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

© www.soinside.com 2019 - 2024. All rights reserved.