我正在将 Go 与 MongoDB 一起使用并创建一个新记录,但是当我将插入的 ID 转换为字符串时,它返回 ObjectID("000000000000000000000000")。
client := connect()
db := client.Database("godb")
// fmt.Println(db)
usersCollection := db.Collection("users")
result, err := usersCollection.InsertOne(ctx, bson.D{
{Key: "title", Value: "The Polyglot Developer Podcast"},
{Key: "author", Value: "Nic Raboy"},
})
if err != nil {
log.Fatal(err)
}
newID := result.InsertedID
fmt.Println("InsertOne() newID:", newID)
fmt.Println("InsertOne() newID type:", reflect.TypeOf(newID))
oid, _ := newID.(primitive.ObjectID)
fmt.Println(oid)
输出
InsertOne() newID: ObjectID("5e947e7036a5c1587fa4a06e")
InsertOne() newID type: primitive.ObjectID
ObjectID("000000000000000000000000")