登录
首页 >  Golang >  Go问答

将字符串类型 URL 参数转换为 MongoDB 查询的方法

来源:stackoverflow

时间:2024-02-28 18:18:26 398浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《将字符串类型 URL 参数转换为 MongoDB 查询的方法》,涉及到,有需要的可以收藏一下

问题内容

我正在尝试通过 get 请求发送的 url 参数从 mongodb 中查找并检索相关数量的字段。

func main() {
    r := mux.newrouter()
    r.handlefunc("/user", createuser).methods("post")
    r.handlefunc("/suggest", searchcity).methods("get") // the route for the function

    fmt.println("server running at port 8080")
    log.fatal(http.listenandserve(":8080", r))

}
func searchcity(w http.responsewriter, r *http.request) {
    //ctx := context.background()
    db := setup() // setup() returns a mongo.database type
    values := r.url.query()
    city := values.get("city_name") // so the route would ultimately be `/suggest?city_name=` (i think?)

    citycollection := db.collection("city")

    cursor, err := citycollection.find(r.context(), city) // options.find().setprojection(projection))
    if err != nil {
        log.fatal(err)
    }

    var citylist []bson.m
    if err = cursor.all(r.context(), &citylist); err != nil {
        log.fatal(err)
    }
    for _, citylist := range citylist {
        fmt.println(citylist["all_names"])
        fmt.println(citylist["country_name"])
    }
}

我特别尝试从集合中返回 all_namescountry_name 字段,并尝试使用 setprojection() 但我可能使用不正确,所以不确定。

但是,我不断收到此错误:

cannot transform type string to a BSON Document: WriteString can only write while positioned on a Element or Value but is positioned on a TopLevel

有没有办法将其转换为 mongodb 驱动程序可接受的格式?


正确答案


documented所示,错误提示需要使用bson包来使用bson对象查询mongodb。

collection.find(ctx, bson.d{{"name", city}})

下面是一个工作示例,我根据您的评论对其进行了测试。

package main

import (
    "context"
    "encoding/json"
    "log"
    "net/http"
    "time"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/bson/primitive"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

func cityHandler(collection *mongo.Collection) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        ctx := r.Context()
        city := r.URL.Query().Get("city_name")
        var q bson.D
        if city != "" {
            q = bson.D{{"name", city}}
        } else {
            q = bson.D{{}}
        }

        cur, currErr := collection.Find(ctx, q)
        if currErr != nil {
            http.Error(w, currErr.Error(), http.StatusInternalServerError)
        }
        defer cur.Close(ctx)

        var result []primitive.M
        if err := cur.All(ctx, &result); err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }

        w.Header().Set("Content-Type", "application/json")
        err := json.NewEncoder(w).Encode(result)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
        }

    }
}

func main() {
    client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://root:example@localhost:27017"))
    if err != nil {
        panic(err)
    }
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    err = client.Connect(ctx)
    if err != nil {
        panic(err)
    }
    defer client.Disconnect(ctx)

    docs := []interface{}{
        bson.D{{"name", "Wuhu"}},
        bson.D{{"name", "Shexian"}},
    }

    collection := client.Database("china").Collection("cities")

    _, err = collection.InsertMany(ctx, docs)
    if err != nil {
        panic(err)
    }

    http.HandleFunc("/", cityHandler(collection))
    log.Fatal(http.ListenAndServe(":8080", nil))

}

以上就是《将字符串类型 URL 参数转换为 MongoDB 查询的方法》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>