2

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

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

当我进行正常查询时这有效,但在 go lang 中它赋予它的值

ObjectIdHex("5d9d90e5ed645489aae6df64")

相反,它不会导致有效的查询。

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

bson.ObjectId("5d9d90e5ed645489aae6df64")

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

Go Lang 处理程序

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 Lang 结构体

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
}
4

1 回答 1

2

请注意,labix.org/v2/mgo不再维护,如果要使用mgo,请github.com/globalsign/mgo改用。或新的官方mongo-go 驱动程序

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,
}

请注意,bson.ObjectIdHex()如果传递的字符串是无效的十六进制对象 ID,则会出现恐慌。在调用之前使用bson.IsObjectIdHex()它来检查它bson.ObjectId()。有关详细信息,请参阅防止 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,
    // ...
}
于 2019-10-09T10:08:07.697 回答