0

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..."
}
j3d
  • 9,492
  • 22
  • 88
  • 172

1 Answers1

3

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)
}
Community
  • 1
  • 1
Paul A. Fortin
  • 315
  • 2
  • 8