1

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")
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Khanakia
  • 723
  • 1
  • 8
  • 20
  • Check the result of type assertion: `oid, ok:=...` and see if `ok` is true. It looks like it is not. Try `oid:=newID.(primitive.ObjectID)`, and the panic msg should tell you what the error is. – Burak Serdar Apr 13 '20 at 15:09
  • 2
    Print `reflect.TypeOf(newID).PkgPath()` and compare to the import in your code. I think you will find that there are two different `primitive` packages in play. – Charlie Tumahai Apr 13 '20 at 15:17
  • @CeriseLimón You are magician :) :) :). How did you know the issue? I had 2 different packages "github.com/mongodb/mongo-go-driver/mongo" and "go.mongodb.org/mongo-driver/mongo" because of that issue was causing. I removed the github.com package and included the go.mongodb.org package. – Khanakia Apr 13 '20 at 16:03
  • 2
    It's clear from the program output that the type assertion failed. If the type assertion failed, then there are two types in play. – Charlie Tumahai Apr 13 '20 at 16:08
  • Thanks Cerise. I am very glad to know further about the issue. – Khanakia Apr 13 '20 at 16:09

1 Answers1

5

You must specify omitempty for the ID!

type User struct {
    ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
}
Kroksys
  • 759
  • 10
  • 15