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" : "aaa@xxx.com"}
if another user submit :
{"username" : "user1", "email" : "aaa2@xxx.com"} //different email
this will successfully inserted. Which is not what I want.
Or, if the user submit:
{"username" : "user2", "email" : "aaa@xxx.com"} //different username
this will still successfully inserted, which is also not what I wanted.
Any idea how to achieve it?