Golang & mgo:如何创建具有 _id、创建时间和上次更新等公共字段的通用实体

Golang & mgo: How to create a generic entity with common fields like _id, creation time, and last update

给出以下 struct

package models

import (
    "time"
    "gopkg.in/mgo.v2/bson"
)

type User struct {
    Id         bson.ObjectId `json:"id" bson:"_id"`
    Name       string        `json:"name" bson:"name"`
    BirthDate  time.Time     `json:"birth_date" bson:"birth_date"`
    InsertedAt time.Time     `json:"inserted_at" bson:"inserted_at"`
    LastUpdate time.Time     `json:"last_update" bson:"last_update"`
}

...这是我将新用户插入 Mongo 集合的方法:

user := &models.User{
    bson.NewObjectId(),
    "John Belushi",
    time.Date(1949, 01, 24),
    time.now().UTC(),
    time.now().UTC(),
}

dao.session.DB("test").C("users").Insert(user)

是否可以让所有其他实体继承一个通用的Entity?我试过这个...

type Entity struct {
    Id         bson.ObjectId `json:"id" bson:"_id"`
    InsertedAt time.Time     `json:"inserted_at" bson:"inserted_at"`
    LastUpdate time.Time     `json:"last_update" bson:"last_update"`
}

type User struct {
    Entity
    Name       string        `json:"name" bson:"name"`
    BirthDate  time.Time     `json:"birth_date" bson:"birth_date"`
}

...但这意味着最终结果如下:

{
    "Entity": {
        "_id": "...",
        "inserted_at": "...",
        "last_update": "..."
    },
    "name": "John Belushi",
    "birth_date": "1949-01-24..."
}

如何在不重复每个 struct 中的公共字段的情况下获得以下结果?

{
    "_id": "...",
    "inserted_at": "...",
    "last_update": "...",
    "name": "John Belushi",
    "birth_date": "1949-01-24..."
}

这已经在 Storing nested structs with mgo 中得到了回答,但是您需要做的就是在匿名内部结构上添加 bson:",inline" 并正常初始化...

这里有一个简单的例子:

package main

import (
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

type Entity struct {
    Id         bson.ObjectId `json:"id" bson:"_id"`
    InsertedAt time.Time     `json:"inserted_at" bson:"inserted_at"`
    LastUpdate time.Time     `json:"last_update" bson:"last_update"`
}

type User struct {
    Entity    `bson:",inline"`
    Name      string    `json:"name" bson:"name"`
    BirthDate time.Time `json:"birth_date" bson:"birth_date"`
}

func main() {
    info := &mgo.DialInfo{
        Addrs:    []string{"localhost:27017"},
        Timeout:  60 * time.Second,
        Database: "test",
    }

    session, err := mgo.DialWithInfo(info)
    if err != nil {
        panic(err)
    }
    defer session.Close()
    session.SetMode(mgo.Monotonic, true)
    //  c := session.DB("test").C("users")

    user := User{
        Entity:    Entity{"123456789098", time.Now().UTC(), time.Now().UTC()},
        Name:      "John Belushi",
        BirthDate: time.Date(1959, time.February, 28, 0, 0, 0, 0, time.UTC),
    }

    session.DB("test").C("users").Insert(user)
}