mongodb - 如何在golang中为嵌套文档设置ObjectId?

标签 mongodb model-view-controller go

型号:

type Vehicle   struct {
    Id          bson.ObjectId `bson:"_vid,omitempty"`
    Brand           string
    Category        string  
    CategorySubject     string
    MakeYear        string
    RegistrationNumber  string
    Model           string
    Price           string
}
func (this *Vehicle)AddToDB(emailId1 string)  {
    sess, db := GetDatabase()
    defer sess.Close()
    c := db.C("user")
    //newId :=Vehicle{}
    /*colQuerier := bson.M{"email": person.Email}
    change := bson.M{"$set": bson.M{"profile" : imgName}}
    err = c.Update(colQuerier, change)*/
    colQuerier := bson.M{"email": emailId1}
    change := bson.M{"$push": bson.M{"myvehicle" : &this}}
    err := c.Update(colQuerier, change)
    if err != nil {
        fmt.Println("not inserted") 
    }
}

当车辆插入myvehicle字段时,其Id值为空。

如何为嵌套车辆的 id 设置值?

最佳答案

MongoDB ObjectId对于未指定 _id 字段的文档(非子文档)自动插入。这是为了唯一地标识该文档。

在上面的例子中,如果您插入嵌套对象(子文档),MongoDB 不会自动插入 Id 字段。

但是,您可以为新推送的车辆文档创建一个 ObjectId(唯一标识符)。例如:

new_object_id := bson.NewObjectId()

另请参阅NewObjectId

关于mongodb - 如何在golang中为嵌套文档设置ObjectId?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41375042/

相关文章:

go - 使用 aws-go-dep 安装无服务器不起作用

mongodb - 恢复丢失的 WiredTiger.wt

带有 MongoDB 的 Java 堆空间

model-view-controller - 从 global.asax 访问 RequestContext

unit-testing - go test 是否同时运行单元测试?

windows - 找不到包 "gopkg.in/validator.v2"错误

ruby-on-rails - rails 3 : how to use active record and mongoid at the same time

node.js - Express JS 和 Mongoose REST API 结构 : best practices?

python - Python 中的包和模块,用于使用 Flask 创建 Web 应用程序

ios - 从 TableView 中的按钮创建菜单下拉菜单