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

huangapple go评论81阅读模式
英文:

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

huangapple
  • 本文由 发表于 2016年12月29日 15:26:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/41375042.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定