skip to Main Content

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


  1. 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 of primitive.ObjectID), it boils down to:

    • either you actually using a custom type (having primitive.ObjectID as its underlying type) such as type MyID primitive.ObjectID instead of primitive.ObjectID exactly
    • or you mixing major driver versions

    Currently 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.

    Login or Signup to reply.
  2. 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 of primitive.ObjectID, which now shall be assigned to the field ID.

    type User struct {
      Id  primitive.ObjectID `bson:"_id"`
    }
        
    
    user1 := User{
        Id: primitive.NewObjectID()
    }
    

    persisting the data into MongoDB collection, invoke the Mongo collection that you would like to insert your data into, in this case

    users_col.InsertOne(ctx, user1)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search