我正在尝试使用mgo(mongodb)创建一个简单的CRUD。
这是我的代码:
package main
import (
"fmt"
"time"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type State struct {
CustomerId string
CreatedOn time.Time
CreatedBy string
Description string
}
type DataStore struct {
session *mgo.Session
err error
}
func (ds *DataStore) getCol(collectionName string) *mgo.Collection {
ds.session, ds.err = mgo.Dial("localhost:27017")
if ds.err != nil {
panic(ds.err)
}
return ds.session.DB("c3po_db").C(collectionName)
}
func (ds *DataStore) GetAll() []State {
var states []State
ds.err = ds.getCol("state").Find(bson.M{}).All(&states)
if ds.err != nil {
panic(ds.err)
}
ds.session.Close()
return states
}
func (ds *DataStore) GetById(customerId string) State {
var state State
ds.err = ds.getCol("state").Find(bson.M{"customerId": customerId}).One(&state)
if ds.err != nil {
panic(ds.err)
}
ds.session.Close()
return state
}
func (ds *DataStore) CreateOrUpdate(state State) bool {
_, ds.err = ds.getCol("state").Upsert(
bson.M{"customerId": state.CustomerId},
bson.M{"$set": bson.M{"description": state.Description, "createdOn": state.CreatedOn, "createdBy": state.CreatedBy}})
if ds.err != nil {
panic(ds.err)
} else {
ds.session.Close()
return true
}
ds.session.Close()
return false
}
func main() {
ds := DataStore{}
state := State{CustomerId: "3", CreatedOn: time.Now(), CreatedBy: "Ivo", Description: "6"}
ds.CreateOrUpdate(state)
fmt.Println(ds.GetById("3"))
}
结果我得到了
{ 0001-01-01 00:00:00 +0000 UTC 0}
它为GetById打印一个空结果。 CreateOrUpdate方法部分工作。它只插入一条新记录,不会更新现有记录。 这是正确的做法吗? 如何使GetById和CreateOrUpdate方法有效?
答案 0 :(得分:0)
以下代码按预期工作
package main
import (
"fmt"
"time"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type State struct {
CustomerId string
CreatedOn time.Time
CreatedBy string
Description string
}
type DataStore struct {
session *mgo.Session
err error
}
func (ds *DataStore) getCol(collectionName string) *mgo.Collection {
ds.session, ds.err = mgo.Dial("localhost:27017")
if ds.err != nil {
panic(ds.err)
}
return ds.session.DB("c3po_db").C(collectionName)
}
func (ds *DataStore) GetAll() []State {
var states []State
ds.err = ds.getCol("state").Find(bson.M{}).All(&states)
if ds.err != nil {
panic(ds.err)
}
ds.session.Close()
return states
}
func (ds *DataStore) GetById(customerId string) State {
var state State
ds.err = ds.getCol("state").Find(bson.M{"customerId": customerId}).One(&state)
if ds.err != nil {
panic(ds.err)
}
ds.session.Close()
return state
}
func (ds *DataStore) CreateOrUpdate(state State) bool {
_, ds.err = ds.getCol("state").Upsert(
bson.M{"customerId": state.CustomerId},
bson.M{"$set": state})
if ds.err != nil {
panic(ds.err)
} else {
ds.session.Close()
return true
}
ds.session.Close()
return false
}
func main() {
ds := DataStore{}
state := State{CustomerId: "3", CreatedOn: time.Now(), CreatedBy: "Ivo", Description: "6"}
ds.CreateOrUpdate(state)
fmt.Println(ds.GetById("3"))
fmt.Println(ds.GetAll())
}