Golang. Insert mgo ObjectId via mongo driver

We are migrating from mgo to mongo driver and we meet a problem with insert mgo/bson “bson.ObjectId” into MongoDB via mongo driver.

For example, I have a struct:

type Default struct {
    ID bson.ObjectId `bson:"_id" json:"id"`
    UserID bson.ObjectId `bson:"user_id" json:"user_id"`
}

When I insert this struct in MongoDB, values have a type “string” and looks like this:

{ 
    "_id" : "a\u0016B\u001b�\u001cqGdt��", 
    "user_id" : "a\u0016B\u001b�\u001cqGdt��"
}

Have anybody ever has the same problem?
Thanks in advance.

What may be happening is you’re using structs that contain fields that are mgo bson.ObjectId type but using the mongo-go-driver BSON marshaler (inserting structs using the mongo-go-driver marshals the struct data as BSON). Because the mgo bson.ObjectId type is an alias of string, the bson.ObjectId fields are being marshaled as string.

If my assumption about your use case is correct, you should replace the bson.ObjectId type with primitive.ObjectID from the "go.mongodb.org/mongo-driver/bson/primitive" package and see if that resolves the issue.

E.g.

type Default struct {
    ID     primitive.ObjectID `bson:"_id" json:"id"`
    UserID primitive.ObjectID `bson:"user_id" json:"user_id"`
}

Can you share a code snippet of how you’re using instances of the Default struct with the mongo-go-driver so I understand your use case better?

1 Like

This is a problem when using:

mongo.NewClient(options.Client().SetRegistry(mgocompat.Registry))

https://pkg.go.dev/go.mongodb.org/mongo-driver/bson/mgocompat@v1.7.1#Registry