I'm having some issues creating unique indexes for some of my data using the official MongoDB driver for Go.
So I have a struct like this:
type Product struct {
ID primitive.ObjectID `json:"_id" bson:"_id"`
Name string `json:"name" bson:"name"`
Price float64 `json:"price" bson:"price"`
Attribute []Attribute `json:"attribute" bson:"attribute"`
Category string `json:"category" bson:"category"`
}
And then I wan to create a unique index for the name
property. I tried to do something like this in my Create
function (for products)
func Create(c echo.Context) error {
//unique index here
indexModel, err := productCollection.Indexes().CreateOne(context.Background(),
IndexModel{
Keys: bsonx.Doc{{"name", bsonx.Int32(1)}},
Options: options.Index().SetUnique(true),
})
if err != nil {
log.Fatalf("something went wrong: %+v", err)
}
//create the product here
p := new(Product)
if err := c.Bind(p); err != nil {
log.Fatalf("Could not bind request to struct: %+v", err)
return util.SendError(c, "500", "something went wrong", "failed")
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
result, _ := productCollection.InsertOne(ctx, p)
return util.SendSuccess(c, result.InsertedID)
}
The problem is I don't exactly know how to pass indexModel
as an option in the context before creating the product. Also, I'm not sure that with what I'm doing, I'm creating the index just once (which is what I want to do). I'd appreciate it if I could be pointed in the right direction on how to do this.
I'm using the echo framework for Go, just in case this provides more context.