I’m having a problem inserting an ObjectId into a doc.
this is the collection sale model
type Sale struct {
ID primitive.ObjectID `bson:"_id,omitempty"`
Client primitive.ObjectID `bson:"client"`
Items []primitive.ObjectID `bson:"items"`
Amounts []int `bson:"amounts"`
Cost float64 `bson:"cost"`
Payment bool `bson:"payment"`
Date time.Time `bson:"date"`
}
before generating the insert I ensured that Sale.Client
has a valid ObjectId value, but when I perform this insert the value becomes binary within the table.
ex:
ObjectId('67103588b9138d78d5ef09a2')
Binary.createFromBase64('ZxA1iLkTjXjV7wmi', 0)
this is the insert code
func CommonInsert(collection string, ctx context.Context, model interface{}) error {
conn, err := config.GetDbConnection(ctx)
if err != nil {
return err
}
c := conn.Database("teste").Collection(collection)
_, err = c.InsertOne(ctx, model)
if err != nil {
return err
}
return nil
}
I generated real mock data for the insert and I still couldn’t force the data to be transformed into ObjectId
2
Answers
Usually when a
primitive.ObjectID
is not being recognized as a MongoDB ObjectId type (but rather an ordinary byte array which is the underlying type ofprimitive.ObjectID
), it boils down to:primitive.ObjectID
as its underlying type) such astype MyID primitive.ObjectID
instead ofprimitive.ObjectID
exactlyCurrently there is a beta v2 major version of the driver, and there is of course the v1. Make sure you don’t mix the 2 major versions: either use v1 or beta v2 everywhere.
Assuming that this is a schema to which we would like to map our data to be persisted in our MongoDB collection, I tend to invoke
primitive.NewObjectID()
, which will generate an instance ofprimitive.ObjectID
, which now shall be assigned to the field ID.persisting the data into MongoDB collection, invoke the Mongo collection that you would like to insert your data into, in this case