douyan1321 2016-04-02 21:09
浏览 91
已采纳

Golang和mgo:如何使用_id,创建时间和最后更新等通用字段创建通用实体

Given the following 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"`
}

... here is how I insert a new user into a Mongo collection:

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)

Is it possible to have a generic Entity all other entities inherit from? I've tried this...

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"`
}

... but this implies a final result like this:

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

How do I get the following result without repeating common fields in each struct?

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

1条回答 默认 最新

  • douchen9855 2016-04-03 02:48
    关注

    This was already answered in Storing nested structs with mgo, but it is very easy all you need to do is add bson:",inline" on the anonymous inner struct and initialize as normal...

    Here a quick example:

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝