Golang jsonapi需要字符串或int,但mongo需要bson.ObjectId
使用go和以下软件包:Golang jsonapi需要字符串或int,但mongo需要bson.ObjectId,go,mgo,json-api,Go,Mgo,Json Api,使用go和以下软件包: github.com/julienschmidt/httprouter github.com/shwoodard/jsonapi gopkg.in/mgo.v2/bson 我有以下结构: type Blog struct{ Posts []interface{} } type BlogPost struct { Id bson.ObjectId `jsonapi:"primary,posts" bson:"_id,omitempty"`
github.com/julienschmidt/httprouter
github.com/shwoodard/jsonapi
gopkg.in/mgo.v2/bson
我有以下结构:
type Blog struct{
Posts []interface{}
}
type BlogPost struct {
Id bson.ObjectId `jsonapi:"primary,posts" bson:"_id,omitempty"`
Author string `jsonapi:"attr,author"`
CreatedDate time.Time `jsonapi:"attr,created_date"`
Body string `jsonapi:"attr,body"`
Title string `jsonapi:"attr,title"`
}
这个路由器处理器:
func (blog *Blog) GetAll(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
if err := jsonapi.MarshalManyPayload(w, blog.Posts); err != nil {
http.Error(w, err.Error(), 500)
}
}
调用处理程序函数时,会抛出错误:
id should be either string or int
这个结构应该是什么样子的,这样我就可以与mgo和jsonapi一起使用了?再创建一个Blog结构,如下所示
type BlogPostVO struct {
Id string `jsonapi:"primary,posts" bson:"_id,omitempty"`
Author string `jsonapi:"attr,author"`
CreatedDate time.Time `jsonapi:"attr,created_date"`
Body string `jsonapi:"attr,body"`
Title string `jsonapi:"attr,title"`
}
并在控制器中使用以下函数来解析
func parseToVO(blog *models.Blog) *models.BlogVO {
bolgVO := models.BlogVO{}
bolgVO.Id = blog.Id.Hex()
bolgVO.Author = blog.Author
bolgVO.CreatedDate = blog.CreatedDate
bolgVO.Body = blog.Body
bolgVO.Title = blog.Title
return &models.Blog
}
这对我来说很有效再创建一个博客结构,如下所示
type BlogPostVO struct {
Id string `jsonapi:"primary,posts" bson:"_id,omitempty"`
Author string `jsonapi:"attr,author"`
CreatedDate time.Time `jsonapi:"attr,created_date"`
Body string `jsonapi:"attr,body"`
Title string `jsonapi:"attr,title"`
}
并在控制器中使用以下函数来解析
func parseToVO(blog *models.Blog) *models.BlogVO {
bolgVO := models.BlogVO{}
bolgVO.Id = blog.Id.Hex()
bolgVO.Author = blog.Author
bolgVO.CreatedDate = blog.CreatedDate
bolgVO.Body = blog.Body
bolgVO.Title = blog.Title
return &models.Blog
}
这对我来说很有效我以前没有使用过jsonapi,但是快速浏览一下,似乎Id字段是一个int字段,我猜bson“\u Id”是在mongodb中创建的,但没有在结构中使用。我以前没有使用过jsonapi,但是快速浏览一下,似乎Id字段是一个int字段,我猜bson“\u Id”在mongodb中创建,但未在结构中使用