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

一个以上的键时,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)

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

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助