dongtanzhu5417 2018-04-14 17:31 采纳率: 100%
浏览 629
已采纳

一个以上的键时,golang mongoDB唯一索引不起作用

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?

  • 写回答

1条回答 默认 最新

  • du512053619 2018-04-15 05:43
    关注

    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)

    too many open files in mgo go server

    Concurrency in gopkg.in/mgo.v2 (Mongo, Go)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?