3 回答

TA貢獻1828條經(jīng)驗 獲得超3個贊
也許是這樣的。首先定義一個返回結(jié)構(gòu)指針的函數(shù):
func NewAbonnement()(ab *Abonnement){
return &Abonnement{Newsletter: false}
}
然后將該函數(shù)稱為 Abonnement 切片文字:
personita := Persone{
Compte : "Standard",
Datei : time.Date(2015, time.February, 12, 04, 11, 0, 0, time.UTC),
Email : "test@test.com",
MDP : "test_mdp",
Type : "T&D",
User : "test_user",
Validation : "validé",
Arrival : []string{},
Clicks : []string{},
Recherches : []string{},
Abonnements : []Abonnement{*NewAbonnement()},
}

TA貢獻1802條經(jīng)驗 獲得超5個贊
擁有嵌套結(jié)構(gòu)的解決方案是:
type Abonnement struct {
Newsletter bool `bson:"newsletter"`
StripeID string `bson:"stripe_id,omitempty"`
StripeSub string `bson:"stripe_sub,omitempty"`
}
type Personne struct {
Compte string `bson:"compte"`
Datei time.Time `bson:"datei"`
Email string `bson:"email"`
MDP string `bson:"mdp"`
Type string `bson:"T&D"`
User string `bson:"user"`
Validation string `bson:"validation"`
Arrival []string `bson:"Arrival"`
Clicks []string `bson:"Clicks"`
Recherches []string `bson:"Recherches"`
Abonnements Abonnement `bson:"abonnements"`
}
然后 :
personita := Personne{
Compte : "Standard",
Datei : time.Date(2015, time.February, 12, 04, 11, 0, 0, time.UTC),
Email : "test@test.com",
MDP : "test_mdp",
Type : "T&D",
User : "test_user",
Validation : "validé",
Abonnements : Abonnement{false,"",""},
}
if err := coll.Insert(personita); err != nil {panic(err)}
這樣,您就可以使用默認值將嵌套的 JSON 添加到 MongoDB。
此外,在這種特殊情況下,StripeID 或 StripeSub 是可選的,因此如果值為空,它們將不會出現(xiàn)在您的數(shù)據(jù)庫中。
- 3 回答
- 0 關(guān)注
- 310 瀏覽
添加回答
舉報