简体   繁体   中英

Golang Mongodb insertOne returns empty ID ObjectID("000000000000000000000000")

I am using Go with MongoDB and creating a New Record but when I convert the insertedID to string it returns 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)

OUTPUT

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

You must specify omitempty for the ID!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM