Primitive.ObjectID 到 Golang 中的字符串

我正在尝试将类型转换primitive.ObjectID为stringGo 中的类型。我正在使用mongo-driver来自go.mongodb.org/mongo-driver.


我尝试使用类型断言


mongoId := mongoDoc["_id"];

stringObjectID := mongoId.(string)

哪个 VSCode 接受。代码被编译,当它到达这个特定的代码行时,它会抛出这个错误


panic: interface conversion: interface {} is primitive.ObjectID, not string


杨__羊羊
浏览 744回答 3
3回答

墨色风雨

错误消息告诉mongoDoc["_id"]is of type interface{},它的值是 type primitive.ObjectID。这不是 a string,它是一个独特的类型。您只能primitive.ObjectID从接口值中键入 assert。如果你想要string这个 MongoDB ObjectId 的表示,你可以使用它的ObjectID.Hex()方法来获取 ObjectId 字节的十六进制表示:mongoId := mongoDoc["_id"]stringObjectID := mongoId.(primitive.ObjectID).Hex()

梦里花落0921

2021 年情况发生了变化。这里有一个更简单的方法。它让用户从模型中询问它来自界面的类型,然后一切都很好var user models.Userquery := bson.M{"$or": []bson.M{{"username": data["username"]}, {"email": data["username"]}}}todoCollection := config.MI.DB.Collection(os.Getenv("DATABASE_COLLECTION_USER"))todoCollection.FindOne(c.Context(), query).Decode(&user)stringObjectID := user.ObjectID.Hex()上面的代码适用于这个接口:type User struct {    ObjectID primitive.ObjectID `bson:"_id" json:"_id"`    // Id        string    `json:"id" bson:"id"`    Username      string    `json:"username" gorm:"unique" bson:"username,omitempty"`    Email         string    `json:"email" gorm:"unique" bson:"email,omitempty"`    Password      []byte    `json:"password" bson:"password"`    CreatedAt     time.Time `json:"createdat" bson:"createat"`    DeactivatedAt time.Time `json:"updatedat" bson:"updatedat"`}因此:这 3 行代码会做得很好:objectidhere := primitive.NewObjectID()stringObjectID := objectidhere.Hex()filename_last := filename_rep + "_" + stringObjectID + "." + fileExt

慕码人2483693

现在你可以做 mongoId.Hex()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go