Golang jsonapi 需要 string 或 int 但 mongo 需要 bson.ObjectId

Golang jsonapi requires string or int but mongo needs bson.ObjectId

使用 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"`
    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 一起使用?

再创建一个博客结构,如下所示

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
}

这对我有用