2016-01-25 20 views
2

我遇到了一个问题,我不知道要采取哪条路径。所以我在这里问。我有一个应用程序,可以有产品,可以有产品的元数据。这些元数据可以从前端创建和删除。所以,假设今天每个产品都有两个元数据(例如Name,Price),那么明天它可以是三个,四个或更多,甚至不到两个。所以这是动态的。我想代表数据如下Mongo DB和Go - 使用动态数据模型

Product = 
{ 
    "_id": mongo 
    "Name": string 
    "Description": string 
    "BasePrice": number 
    "CreatedBy": user mongo _id 
    "CreatedAt": timestamp 
    "ModifiedAt": timestamp 
    "MetaData": BSON object (having all the keys from ProductMetadata collection and their values. e.g. {"Category": "table ware", "Material": "oak wood, copper", "Length": 5.6}) 

} 

ProductMetadata = 
{ 
    "_id": mongo 
    "Name": string (e.g. - "Category" or "Material" or "Height") 
    "Type": string (indicating what kind of value it can hold like string/integer/array. e.g. - "string") 
    "CreatedAt": timestamp 
    "ModifiedAt": timestamp 
} 

正如你可以看到这是如此具有代表模型是不可能的代码级的结构的纯动态情况。

我的问题是,如何使用mgo和Go lang来实现这样的事情?如果我需要使用反射,那么可以请一些人指向一个好的博客/教程,我可以获得更多信息。或者,如果您认为在建模数据的方法中存在根本性问题,那么请纠正我以便使用Go轻松实现。

在Python中,实现它不会有问题。我知道。但是我对Go的实现感到困惑。

请帮忙。

在此先感谢

+0

会这样HTTP ://stackoverflow.com/questions/18340031/unstructured-mongodb-collections-with-mgo帮助? –

+0

谢谢我认为这是我想要的:) – SRC

回答

3

如果键元数据是唯一的,为什么不使用的地图。

这意味着你的产品结构是这样的:

struct Product { 
    ID  bson.ObjectId `bson:"_id,omitempty"` 
    Name string 
    Description string 
    ... omitted other fields ... 
    MetaData map[string]map[string]interface{} // map of string -> map of string -> anything 
} 

如果你能有一个给定的元数据,即多个实例:2类,使用一个清单:

struct Product { 
    ID  bson.ObjectId `bson:"_id,omitempty"` 
    Name string 
    Description string 
    ... omitted other fields ... 
    MetaData []map[string]interface{} // list of maps of string -> anything 
} 
+0

这也是一个很好的解决方案David。我会试试这个。谢谢 – SRC

+0

您可能想要使用https://godoc.org/gopkg.in/mgo.v2/bson#M代替map [string] interface {} –

+0

对bson.M.唯一让我厌倦的理由是它会将bson包泄露到代码的其余部分,无论您想要创建该映射的新文本版本。我通常会尽可能减少第三方进口,所以稍后当我不可避免地改变我的矿时,我不会在某个特定目的使用什么库。 –