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,如下代码所示:

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

如果不想自己调用bson.NewObjectId,想让mongodb自动生成ID怎么办呢?有两种办法

1.使用bson.M构建

在使用mongodb插入文档传参的时候,可以用bson.M构建参数传入Insert

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

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

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

还有一种标签方式也可以,如下:

type BookExt struct {
    ID       bson.ObjectId `bson:"-"`
    Title    string        `bson:"title"`
    SubTitle string        `bson:"subTitle"`
    Author   string        `bson:"author"`
}
`bson:"-"`表示完全忽略此字段,但是也带来个问题,就是从mongodb查询时,使用此结构体作为返回参数,也会忽略此字段,结果中没有读出_id
所以推荐第一种标签方式.

posted on 2019-06-12 11:38  凄夜  阅读(1600)  评论(0编辑  收藏  举报

导航