我是 golang 的新手,他是從動態類型語言遷移過來的。我面臨著如何編寫具有許多類別/子類別的目錄的問題——復雜的分類法。例如:鞋帶 > 鞋履 > 男裝 > 鞋履 > 服裝 > 首頁 > 分類我使用 mongodb 作為后端。在這種情況下,我無法理解如何編寫 CRUD 操作?如果我像往常一樣處理所有查詢:func RunFindAllQuery(document interface{}, m bson.M, mongoSession *mgo.Session, conn Conn) (err error) {sessionCopy := mongoSession.Copy()defer sessionCopy.Close()collection:= sessionCopy.DB(conn.Database).C(conn.Collection) err = collection.Find(m).All(document)if err != nil { log.Printf("RunQuery : ERROR : %s\n", err)} return err}我需要定義很多類型:鞋子!= 汽車。type Shoes struct { Id bson.ObjectId `bson:"_id"` Name string `bson:"name"` Description string `bson:"descriprion"` Size float `bson:"size"` Color float `bson:"color"` Type float `bson:"type"` ShoeHeight float `bson:"shoeheight"` PlatformHeight float `bson:"platformheight"` Country float `bson:"country"`}type Car struct { Id bson.ObjectId `bson:"_id"` Name string `bson:"name"` Model CarModel `bson:"name"` Description string `bson:"descriprion"` Color float `bson:"color"` Height float `bson:"height"` Fueltype string `bson:"fueltype"` Country float `bson:"country"`}我的代碼將被復制粘貼:var carobjFindAll []Carm := bson.M{"description": "description"}_ = RunFindAllQuery(&carobjFindAll, m, mongoSession, conn)for cur := range carobjFindAll { fmt.Printf("\nId: %s\n", carobjFindAll[cur].Id) fmt.Printf("\nColor: %s\n", carobjFindAll[cur].Color)}var shoesobjFindAll []Shoesm_shoes := bson.M{"description": "shoes_description"}_ = RunFindAllQuery(&shoesobjFindAll, m_shoes, mongoSession, conn)for cur_shoe := range shoesobjFindAll { fmt.Printf("\nId: %s\n", shoesobjFindAll[cur_shoe].Id) fmt.Printf("\nColor: %s\n", shoesobjFindAll[cur_shoe].Color)}PS:對不起我的英語
1 回答

慕碼人2483693
TA貢獻1860條經驗 獲得超9個贊
我不是 MongoDB 專家,但這是我的看法:
由于您有很多類別,因此您不必為每種類型編寫結構體,因為它既繁瑣又不可靠。
相反,您應該直接使用bson.M
類型,它基本上是map[string]interface{}
類型的別名。
- 1 回答
- 0 關注
- 232 瀏覽
添加回答
舉報
0/150
提交
取消