英文:
How to set ObjectId for nested document in golang?
问题
模型:
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")
    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")
    }
}
当将Vehicle推送到myvehicle字段时,Id的值为空。
如何为嵌套的Vehicle的id设置一个值?
英文:
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
得分: 2
MongoDB ObjectId 是自动插入的,用于没有指定 _id 字段的文档(非子文档)。这是为了唯一标识文档。
在你上面的情况中,如果你插入一个嵌套对象(子文档),Id 字段不会被 MongoDB 自动插入。
但是,你可以为新推送的车辆文档创建一个 ObjectId(唯一标识符)。例如:
new_object_id := bson.NewObjectId()
另请参阅 NewObjectId。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论