Golang& mgo:如何使用_id,创建时间和上次更新等常用字段创建通用实体

时间:2016-04-02 21:09:20

标签: json go mgo

鉴于以下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..."
}

1 个答案:

答案 0 :(得分:2)

这已在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)
}