dongqian1028 2016-12-29 07:26
浏览 193
已采纳

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

Model:

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") 
    }
}

The value of Id of Vehicle is empty when it's pushed into myvehicle field.

How do I set a value for the nested Vehicle's id ?

  • 写回答

1条回答 默认 最新

  • douwen9534 2017-01-05 07:12
    关注

    MongoDB ObjectId is auto inserted for document (not sub-document) that does not specify _id field. This is to uniquely identify the document.

    In your case above, if you are inserting a nested object (sub-document) the Id field would not be auto-inserted by MongoDB.

    You can however create an ObjectId (unique identifier) for the newly pushed Vehicle document. For example:

    new_object_id := bson.NewObjectId()
    

    See also NewObjectId

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)