如何编写多个类别的目录(分类法>> 100)?

Val*_*yov 9 go

我是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
}
Run Code Online (Sandbox Code Playgroud)

我需要定义很多类型:鞋子!=汽车.

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"`
}
Run Code Online (Sandbox Code Playgroud)

我的代码将是copypaste:

var carobjFindAll []Car
m := 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 []Shoes
m_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)
}
Run Code Online (Sandbox Code Playgroud)

PS:抱歉我的英文

Elw*_*nar 2

我不是 MongoDB 专家,但我的看法是:

由于您有很多类别,因此您没有必要为每种类型编写一个结构,因为它既挑剔又不可靠。

相反,您应该直接使用类型bson.M,它基本上是类型的别名map[string]interface{}