type (
Id struct {
// I previously forgot to add the `ID` field in my question, it is present in my code but not on this question as @icza pointed it out to me
ID bson.ObjectId `json:"id" bson:"_id"`
}
User struct {
// When using anonymous struct, upon returning the collection, each of the document will have an empty `id` field, `id: ""`
Id
Email string `json:"email" bson:"email"`
...
}
// This works
User2 struct {
ID bson.ObjectId `json:"id" bson:"_id"`
Email string `json:"email" bson:"email"`
}
)
まだ匿名の構造体の概念を完全に理解していない可能性があります。上記の例では、コレクションからすべてのユーザーを照会すると、id
フィールドは空の文字列""
になります。しかし、User
構造体のIDフィールドを直接定義すると、id
が正常に表示されます。これは匿名の構造体のためではありませんか?基本的に構造体を拡張するので、繰り返し入力する必要はありません。匿名の構造体が空のフィールド値を返します
その他の例:
type SoftDelete struct {
CreatedAt time.Time `json:"created_at" bson:"created_at"`
UpdatedAt time.Time `json:"updated_at" bson:"updated_at"`
DeletedAt time.Time `json:"deleted_at" bson:"deleted_at"`
}
type UserModel struct {
SoftDelete
}
type BlogPost struct {
SoftDelete
}
は申し訳ありませんがおお、私は 'を入力するのを忘れ:
は、関連する質問+ asnwerを参照してください:
は、代わりにあなたは期待通りまだ動作します
Id
User
に埋め込む、Id
にそれを定期的にフィールドを作ることができます第1のコードブロック内の「ID」を含む。実際に私のコードには、この質問に追加するのを忘れてしまっただけです。 'inline'タグを指摘してくれてありがとう。それは私のためにそれをした、おかげでヒープ! Btw、あなたは今私の2つの「mgo」質問のうち2つに合格して答えました! :) – borislemke