查找功能的通用映射是如何创建的?

时间:2019-04-05 09:46:56

标签: mongodb go mgo

我正在看这个例子。  我永远不会想出这样的解决方案,我会选择bson.raw。

type Movie struct {
    ID        bson.ObjectId `json:"id" bson:"_id,omitempty"`
    Name      string        `json:"name" bson:"name"`
    Year      string        `json:"year" bson:"year"`
    Directors []string      `json:"directors" bson:"directors"`
    Writers   []string      `json:"writers" bson:"writers"`
    BoxOffice BoxOffice     `json:"boxOffice" bson:"boxOffice"`
}

GetMovie函数从MongoDB读取数据并返回JSON

func (db *DB) GetMovie(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    w.WriteHeader(http.StatusOK)
    var movie Movie
    err := db.collection.Find(bson.M{"_id": bson.ObjectIdHex(vars["id"])}).One(&movie)
    if err != nil {
        w.Write([]byte(err.Error()))
    } else {
        w.Header().Set("Content-Type", "application/json")
        response, _ := json.Marshal(movie)
        w.Write(response)
    }

}

我不明白通用地图bson.M是如何创建的。作者为什么使用bson.ObjectIdHex(vars["id"]

1 个答案:

答案 0 :(得分:4)

bson.M是一张地图:

type M map[string]interface{}

这:

bson.M{"_id": bson.ObjectIdHex(vars["id"])}

composite literal,创建类型为bson.M的值。它有一对,其中键是"_id",关联值是函数bson.ObjectId返回的bson.ObjectIdHex()

要查找和返回的文档ID最有可能以vars["id"]中的十六进制字符串形式出现,并且bson.ObjectIdHex()将其转换(解析)为ObjectId

提示:按ID查询文档,使用Collection.FindId更容易,例如:

err := db.collection.FindId(bson.ObjectIdHex(vars["id"])).One(&movie)

如果在vars["id"]中存储了无效的ID,也可以避免运行时出现恐慌,您可以先使用bson.IsObjectIdHex()对其进行检查。有关详细信息,请参见Prevent runtime panic in bson.ObjectIdHex

此外,将结果编组为字节片,然后将其写入响应效率不高,可以使用json.Encoder将响应流式传输到输出。有关详细信息,请参见Ouput json to http.ResponseWriter with template