package main
import (
"fmt"
"
labix.org/v2/mgo"
"
labix.org/v2/mgo/bson"
)
const (
DBHOST = "localhost"
DBNAME = "test5"
)
var (
mgoSession *mgo.Session
userDB *mgo.Database
userR *userRepository = new(userRepository)
communityDB *mgo.Database
communityR *communityRepository = new(communityRepository)
)
type (
User struct {
Id bson.ObjectId `bson:"_id,omitempty" json:"id"`
Email string `json:"email"`
Password string `json:"password"`
}
Community struct {
Id bson.ObjectId `bson:"_id,omitempty" json:"id"`
Name string `json:"name"`
Owner *User `json:"owner"`
}
communityRepository struct {
Collection *mgo.Collection
}
userRepository struct {
Collection *mgo.Collection
}
)
func main() {
var (
err error
)
// Connect to Mongo
mgoSession, err = mgo.Dial(DBHOST)
if err != nil {
panic(err)
}
defer mgoSession.Close()
userDB = mgoSession.DB(DBNAME)
userR.Collection = userDB.C("users")
communityDB = mgoSession.DB(DBNAME)
communityR.Collection = communityDB.C("communities")
u := new(User)
u.Id = bson.NewObjectIdWithTime(bson.Now())
u.Email = "darko"
u.Password = "pass"
userR.Create(u)
u1, err := userR.FindOneByEmail("darko")
c := new(Community)
c.Id = bson.NewObjectId()
c.Name = "commy"
c.Owner = u1
communityR.Create(c)
}
func (r userRepository) Create(user *User) (err error) {
if user.Id.Hex() == "" {
user.Id = bson.NewObjectId()
}
_, err = r.Collection.UpsertId(user.Id, user)
return
}
func (r userRepository) FindOneByEmail(email string) (result *User, err error) {
result = new(User)
err = r.Collection.Find(bson.M{"email": email}).One(result)
return
}
func (r communityRepository) Create(community *Community) (err error) {
if community.Id.Hex() == "" {
community.Id = bson.NewObjectId()
}
_, err = r.Collection.UpsertId(community.Id, community)
return
}
func (u *User) GetBSON(raw bson.Raw) error {
fmt.Printf("raw:%s\n", raw)
return raw.Unmarshal(u)
}
func (u *User) SetBSON() (interface{}, error) {
fmt.Printf("set:%s\n", u)
return u.Id.Hex(), nil
}
########
There is no output
It should output at least either raw: or set: