How to make user's email unique in mongoDB?

核能气质少年 提交于 2020-05-07 18:37:27

问题


I am making a collection of user's data. This will be pretty basic consisting of user's email, user's password (hashed), and an array of strings.

{
    email: 'user@example.com',
    password: 'password hash',
    arr: []
}

I want to make sure that there can't be two inserts with the same email. I read that the _id of mongoDB is unique by default, and it uses some special data structure for improved performance.

How can I make sure that the email remains unique, and if possible can I leverage the performance benefits provided by the _id field ?

Edit: I also want to make sure that there are no null values for email and that there are no documents which do not contain the email field.


回答1:


You can do it by creating a unique index for your email field.

http://docs.mongodb.org/manual/tutorial/create-a-unique-index/

Scott




回答2:


Use unique keyword, or simply make _id value to be email.

db.collection.createIndex( { email: 1 }, { unique: true } )



回答3:


Mongodb ensureIndex has been deprecated, use createIndex instead.

db.collection.createIndex( { email: 1 }, { unique: true } )



来源:https://stackoverflow.com/questions/28514120/how-to-make-users-email-unique-in-mongodb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!