Find 函数的通用地图是如何创建的?

How Find function's generic map was created?

我正在看这个例子。 我永远不会想出这样的解决方案,我会选择 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 和 returns 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"]?

bson.M 是引擎盖下的地图:

type M map[string]interface{}

还有这个:

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

是一个composite literal creating a value of type bson.M. It has a single pair where key is "_id" and the associated value is a bson.ObjectId returned by the function bson.ObjectIdHex().

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

提示:通过ID查询文档,使用Collection.FindId更简单,例如:

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

此外,为了避免在 vars["id"] 中存储无效 ID 时出现运行时恐慌,您可以使用 bson.IsObjectIdHex() to check it first. For details, see .

另外,将结果编组到一个字节片中然后将其写入响应是低效的,可以使用 json.Encoder. For details, see .

将响应流式传输到输出