Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Golang jsonapi需要字符串或int,但mongo需要bson.ObjectId_Go_Mgo_Json Api - Fatal编程技术网

Golang jsonapi需要字符串或int,但mongo需要bson.ObjectId

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"`

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

再创建一个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中创建,但未在结构中使用