【问题标题】:Golang & mgo: How to create a generic entity with common fields like _id, creation time, and last updateGolang 和 mgo:如何创建具有通用字段(如 _id、创建时间和上次更新)的通用实体
【发布时间】:2016-07-22 13:58:25
【问题描述】:

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

【问题讨论】:

标签: json go mgo


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 2010-09-18
    • 2022-01-24
    相关资源
    最近更新 更多