go mongodb 使用mgo remove碰到的问题

用go的mgo来使用mongo 碰到的问题总结:前端

struct tag

若是须要得到 id ,那么 须要将 id定义为 bson.ObjectId 类型json

type Person struct {
    Id         bson.ObjectId   `bson:"_id,omitempty" json:"-"`
    FirstName  string          `bson:"firstName" json:"firstName"`
    MiddleName string          `bson:"middleName,omitempty" json:"middleName,omitempty"`
    LastName   string          `bson:"lastName" json:"lastName"`
    Inserted   time.Time       `bson:"inserted" json:"-"`
}

使用 id remove

由于使用了go的模板,因此在 前端传到后端的过程当中形成直接传值错误,因此须要先将获得的 id 进行处理后端

直接将id传到后端的样子:ObjectIdHex("57be5b3c42d8b3683704c54e")code

这个样子是使用了 bson.ObjectIdstring()方法rem

// String returns a hex string representation of the id.
// Example: ObjectIdHex("4d88e15b60f486e428412dc9").
func (id ObjectId) String() string {
	return fmt.Sprintf(`ObjectIdHex("%x")`, string(id))
}

可是咱们须要的只是 4d88e15b60f486e428412dc9 这部分,string

  • 在模板中加入自定义方法hex, 进行转换
"hex": func(val bson.ObjectId) string {
			return val.Hex()
		},

而后将这个id 传到后台后用 bson.ObjectIdHex()再包装,而后调用删除方法it

err = db.C("info").RemoveId(bson.ObjectIdHex(id))

或

err := collection.Remove(bson.M{"_id": id})
相关文章
相关标签/搜索