我有一个在我的逻辑中使用的结构
type MyStruct struct {
F1 string
F2 string
}
我想将类型的值保存MyStruct
到文档数据库中,只添加一个时间戳。所以我创建了一个新的结构嵌入MyStruct
type MyStructForDB {
MyStruct
Ts time.Time
}
在 saveToDb 函数中,我执行以下操作
func saveToDb(s MyStruct) {
sDb := MyStructForDB{
s, time.Now()
}
// execute the update on the DB
}
如果我这样做,在数据库上我会找到一个具有以下结构的文档
{
myStruct: {
f1: "a value" // any value that was in s.F1
f2: "another value" // any value that was in s.F2
}
ts: 2020-06-26T14:15:07.050Z // a timestamp value
}
虽然这没问题,myStruct
但我宁愿不看财产,而是看像这样的更扁平的文件
{
f1: "a value" // any value that was in s.F1
f2: "another value" // any value that was in s.F2
ts: 2020-06-26T14:15:07.050Z // a timestamp value
}
我知道我可以逐个复制字段或使用反射,但我只是想知道是否有更简单的方法来实现这一点
在 DocumentDB 中,您可以使用包的inline
标志bson
来展平嵌入的结构
type MyStructForDB {
MyStruct `bson:",inline"`
Ts time.Time
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句