型号:
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/