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})
相關文章
相關標籤/搜索