簡體   English   中英

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

[英]Golang Mongodb insertOne returns empty ID ObjectID("000000000000000000000000")

我正在使用 Go 和 MongoDB 並創建一個新記錄,但是當我將 insertedID 轉換為字符串時,它返回 ObjectID("0000000000000000000000000")。

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)

OUTPUT

InsertOne() newID: ObjectID("5e947e7036a5c1587fa4a06e")
InsertOne() newID type: primitive.ObjectID
ObjectID("000000000000000000000000")

您必須為 ID 指定omitempty

type User struct {
    ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM