mongodb插入文档时不传ObjectId

type BookExt struct {
    ID       bson.ObjectId `bson:"_id"`
    Title    string        `bson:"title"`
    SubTitle string        `bson:"subTitle"`
    Author   string        `bson:"author"`
}

以上结构体,在经过此结构体对象做为参数传入Insert插入文档时,必须经过bson.NewObjectId建立ID,以下代码所示:mongodb

aBook := BookExt{
    ID:bson.NewObjectId(),
    Title:    "Go",
    SubTitle: "Go",
    Author:   "GoBj",
}   
c.Insert(&aBook)

若是不想本身调用bson.NewObjectId,想让mongodb自动生成ID怎么办呢?有两种办法spa

1.使用bson.M构建code

在使用mongodb插入文档传参的时候,能够用bson.M构建参数传入Insert对象

c.Insert(bson.M{
    "title":    "Go",
    "subTitle": "Go",
    "author":   "GoBj",
})

2.在结构体中,使用tag标签blog

type BookExt struct {
    ID       bson.ObjectId `bson:"_id,omitempty"` 
    Title    string        `bson:"title"`
    SubTitle string        `bson:"subTitle"`
    Author   string        `bson:"author"`
}

使用以上 `bson:"_id,omitempty"`标签,意思是当传入的_id是空时,将忽略该字段,因此当插入到mongodb时,发现此字段为空,mongodb将自动生成_id文档

还有一种标签方式也能够,以下:string

type BookExt struct {
    ID       bson.ObjectId `bson:"-"`
    Title    string        `bson:"title"`
    SubTitle string        `bson:"subTitle"`
    Author   string        `bson:"author"`
}
`bson:"-"`表示彻底忽略此字段,可是也带来个问题,就是从mongodb查询时,使用此结构体做为返回参数,也会忽略此字段,结果中没有读出_id因此推荐第一种标签方式.
相关文章
相关标签/搜索