Golang Mongodb insertOne 返回空 ID ObjectID("000000000000000000000000")

Ama*_*sal 1 go google-app-engine-golang

我正在使用 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)
Run Code Online (Sandbox Code Playgroud)

输出

InsertOne() newID: ObjectID("5e947e7036a5c1587fa4a06e")
InsertOne() newID type: primitive.ObjectID
ObjectID("000000000000000000000000")
Run Code Online (Sandbox Code Playgroud)

Kro*_*sys 5

您必须为 ID指定omitempty !

type User struct {
    ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
}
Run Code Online (Sandbox Code Playgroud)