mgo正在将objectid设置为objectidhex,Mongodb似乎无法读取它

yzuktlbb  于 2022-11-28  发布在  Go
关注(0)|答案(1)|浏览(129)

我尝试使用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
}
ogq8wdun

ogq8wdun1#

请注意,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"))只不过是类型转换。您将十六进制对象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()对其进行检查。有关详细信息,请参阅防止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,
    // ...
}

相关问题