英文:
Golang jsonapi requires string or int but mongo needs bson.ObjectId
问题
使用mgo和jsonapi时,应该如何修改结构体以解决出现"id should be either string or int"错误的问题?
修改BlogPost结构体的Id字段的类型为string或int,以满足jsonapi的要求。修改后的结构体如下:
type BlogPost 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"`
}
请注意,这里使用了反引号(`)来标记结构体字段的标签。这些标签用于指定jsonapi和mgo的序列化和反序列化规则。
英文:
Playing with go and the following packages:
github.com/julienschmidt/httprouter
github.com/shwoodard/jsonapi
gopkg.in/mgo.v2/bson
I have the following structs:
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"`
}
and this router handler:
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)
}
}
When the handler function is called it spits out the error:
id should be either string or int
How should this struct look so I can use it with mgo and jsonapi?
答案1
得分: 2
创建一个类似下面的 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 {
blogVO := models.BlogVO{}
blogVO.Id = blog.Id.Hex()
blogVO.Author = blog.Author
blogVO.CreatedDate = blog.CreatedDate
blogVO.Body = blog.Body
blogVO.Title = blog.Title
return &blogVO
}
这对我起作用了。
英文:
Create one more struct of Blog like below
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"`
}
and use the below function in your controller to parse
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
}
this worked for me
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论