我正在尝试在Go中将类型primitive.ObjectID转换为string类型。我使用的是来自go.mongodb.org/mongo-driver的mongo-driver。
我尝试使用类型断言,比如
mongoId := mongoDoc["_id"];
stringObjectID := mongoId.(string)这是VSCode接受的。代码被编译,当它到达这一特定的代码行时,它抛出这个错误
panic: interface conversion: interface {} is primitive.ObjectID, not string发布于 2020-03-26 18:26:57
错误消息告诉mongoDoc["_id"]的类型为interface{},该类型包含primitive.ObjectID类型的值。这不是string,它是一个不同的类型。您只能从接口值输入assert primitive.ObjectID。
如果您想要此MongoDB ObjectId的string表示,可以使用它的ObjectID.Hex()方法获取ObjectId字节的十六进制表示:
mongoId := mongoDoc["_id"]
stringObjectID := mongoId.(primitive.ObjectID).Hex()发布于 2021-09-22 18:14:14
2021年,情况发生了变化。这里有一个更简单的方法。它将用户从模型中提取出来,从界面中询问它是哪种类型,然后一切正常
var user models.User
query := 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发布于 2021-11-27 14:33:14
现在你可以只做mongoId.Hex()
https://stackoverflow.com/questions/60864873
复制相似问题