a bson struct tag to create a unique index just like gorm

I'm trying to find a bson struct tag to create a unique index just like the one in the image attached to this post but for mongodb. i tried searching and i found nothing Close to what i need but this stackoverflow post https://stackoverflow.com/questions/30831316/how-to-specify-a-struct-with-a-multi-column-unique-index-for-gorm

2 points · 2 comments · view on lemmy.world

2 Comments

m29h@feddit.nl · 1 pts · 3y (1 reply)

Why don't you just set the id to whatever ( e.g UUID) you want in your struct constructor. Alternatively I guess there are also mongodb specific client libraries for Go

The documentation of package mongo says for example ``` If the document does not have an _id field when transformed into BSON, one will be added automatically to the marshalled document.

noornee@lemmy.ml · 1 pts · 3y

Hello, Thanks for responding. ^^

i didn't want to make any changes to the id field.

i have a user struct like this.

type User struct {
	ID         primitive.ObjectID `bson:"_id,omitempty" json:"id"`
	FirstName  string             `bson:"firstname" json:"firstname"`
	LastName   string             `bson:"lastname" json:"lastname"`
	Email      string             `bson:"email" index:"email" json:"email"`
 }

i wanted the Email field to be unique, just like the ID. so when a new user tries to create an account with the same email, it'll return an error.

it isn't a problem anymore because i figured out a way... i created a custom struct tag that validates whether a user with the same email exist in the database.