登录
首页 >  Golang >  Go问答

将 objectid 切换为 objectidhex 后,Mongodb 无法正确读取

来源:stackoverflow

时间:2024-02-28 09:06:24 316浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《将 objectid 切换为 objectidhex 后,Mongodb 无法正确读取》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

我正在尝试使用 objectid 进行查询,通常在 mongodb 中你会做这样的事情

db.collection.findone({"_id":objectid("5d9d90e5ed645489aae6df64")})

当我执行正常查询时,这会起作用,但在 go lang 中,它给出了

的值
objectidhex("5d9d90e5ed645489aae6df64")

这不会导致有效的查询。

我已经多次阅读 mgo 文档并尝试使用

bson.objectid("5d9d90e5ed645489aae6df64")

但它仍然使它成为我不明白的十六进制。我尝试了几种不同的组合,但它们几乎都只是在黑暗中拍摄。

go 语言处理程序

package userhandlers

import (
    "log"
    "net/http"
    //"fmt"
    //"go.mongodb.org/mongo-driver/bson/primitive"
    //"go.mongodb.org/mongo-driver/bson"
    "labix.org/v2/mgo/bson"

    //services
    databaseservice "malikiah.io/services/databaseservice"
    passwordservice "malikiah.io/services/passwordservice"

    //structs
    userstructs "malikiah.io/structs/userstructs"
    databasestructs "malikiah.io/structs/databasestructs"
)

func loginhandler(response http.responsewriter, request *http.request) {
    response.header().set("content-type", "application/json")
    response.writeheader(http.statusok)

    databasequery := databasestructs.find{
        id: bson.objectid(request.formvalue("_id")),
        mongocollection: "users",
        criteria: "_id",
        criteriavalue: "",
        findall: false,
    }
    log.println(databasequery)
    databaseservice.login(databasequery)
}

go 语言结构

package databasestructs

import (
    //"go.mongodb.org/mongo-driver/bson/primitive"
    "labix.org/v2/mgo/bson"
)

type find struct {
    id                      bson.objectid   `json:"_id,omitempty" bson:"_id,omitempty"`
    mongocollection         string              `json:"mongocollection,omitempty" bson:"mongocollection,omitempty"`
    criteria                string              `json:"criteria,omitempty" bson:"criteria,omitempty"`
    criteriavalue           string              `json:"criteriavalue,omitempty" bson:"criteriavalue,omitempty"`
    findall                 bool                `json:"findall,omitempty" bson:"findall,omitempty"`
}

go 语言函数

package databaseservice

import (
    "context"
    "log"

    //Structs
    userstructs "malikiah.io/structs/userStructs"
    databasestructs "malikiah.io/structs/databaseStructs"

    //"go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "gopkg.in/mgo.v2/bson"

)

func Find(databaseQuery databasestructs.Find) (result string) {
    // Set client options
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

    // Connect to MongoDB
    client, err := mongo.Connect(context.TODO(), clientOptions)

    // Database name
    db := client.Database("malikiah")
    collection := db.Collection(databaseQuery.MongoCollection)

    if err != nil {
        log.Fatal(err)
    }

    if databaseQuery.Criteria == "_id" {
        log.Println(databaseQuery.ID)
        result := collection.FindOne(context.TODO(), bson.M{databaseQuery.Criteria: databaseQuery.ID}).Decode(&result)
        log.Println(result)
    } else if databaseQuery.Criteria == "" {

    } else if databaseQuery.FindAll == true {

    } else {

    }
    return
}

解决方案


请注意,labix.org/v2/mgo 不再维护,如果您想使用 mgo,请使用 github.com/globalsign/mgo 代替。或者新的官方 mongo-go driver

bson.ObjectId 是以 string 作为其基础类型的类型:

type objectid string

所以当你像这样填充你的对象时:

databasequery := databasestructs.find{
    id: bson.objectid(request.formvalue("_id")),
    mongocollection: "users",
    criteria: "_id",
    criteriavalue: "",
    findall: false,
}

bson.objectid(request.formvalue("_id")) 只不过是类型 conversion。您将十六进制对象 id 字符串转换为 bson.objectid,但这不是你想要什么。您想要解析十六进制对象id。为此,请使用 bson.ObjectIdHex() 函数

databasequery := databasestructs.find{
    id: bson.objectidhex(request.formvalue("_id")),
    mongocollection: "users",
    criteria: "_id",
    criteriavalue: "",
    findall: false,
}

请注意,如果传递的字符串是无效的十六进制对象 id,bson.objectidhex() 将发生混乱。在调用 bson.objectid() 之前使用 bson.IsObjectIdHex() 检查它。详情请见Prevent runtime panic in bson.ObjectIdHex

如果您使用官方驱动程序而不是 mgo,则可以使用 primitive.ObjectIDFromHex() 函数来创建 objectid,例如:

id, err := primitive.ObjectIDFromHex(request.FormValue("_id"))
if err != nil {
    // Handle error
    return
}
// If no error, you may use it:
databaseQuery := databasestructs.Find{
    ID: id,
    // ...
}

本篇关于《将 objectid 切换为 objectidhex 后,Mongodb 无法正确读取》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

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