I want to insert data into user collection upon registration.
Thus, email and username are unique and can't be duplicate. I use mgo.v2 for mongodb driver and mgo.Index
to defined the unique keys.
Here is what I did:
type User struct {
ID bson.ObjectId `bson:"_id,omitempty" json:"_id,omitempty"`
Username string `bson:"username" json:"username"`
PW string `bson:"pw" json:"pw"`
Email string `bson:"email" json:"email"`
}
func (u *User) Add() error {
mConn := mongodb.Conn()
defer mConn.Close()
index := mgo.Index{
Key: []string{"username", "email"},
Unique: true,
}
c := mConn.DB(DB).C(Collection)
err := c.EnsureIndex(index)
if err != nil {
return err
}
u.CreatedAt = time.Now()
err = c.Insert(u)
return err
}
The problem is I want the username and email completely unique. Which means, if the username
and email
have been inserted into collection, they will not able to insert again.
But right now, it only check the email AND username together to determine if they are both existed in same document. which means if someone submit same email but different username,it will still get through the insert process.
For eg: If we already have this in our collection
{"username" : "user1", "email" : "[email protected]"}
if another user submit :
{"username" : "user1", "email" : "[email protected]"} //different email
this will successfully inserted. Which is not what I want.
Or, if the user submit:
{"username" : "user2", "email" : "[email protected]"} //different username
this will still successfully inserted, which is also not what I wanted.
Any idea how to achieve it?
The unique
index with keys ["username", "email"]
ensures the username-email pairs to be unique.
What you want is both usernames and emails to be unique individually, so create 2 unique indices, one with username
and one with email
key:
for _, key := range []string{"username", "email"} {
index := mgo.Index{
Key: []string{key},
Unique: true,
}
if err := c.EnsureIndex(index); err != nil {
return err
}
}
Note that individually unique usernames and emails implicitly ensure unique username-email pairs too.
On a side note: you should not connect and check indices each time you need to interact with MongoDB. Instead you should only connect and ensure indices once, on startup. See these questions for details:
mgo - query performance seems consistently slow (500-650ms)