8

I have a user.js model in my node app, and I'd like the username and a few other fields to be unique. In my model file I have properly declared the unique type seen below:

// User Schema
const UserSchema = new Schema({

    // PERSONAL USER INFO
    username: {
        type: String,
        required: true,
        index: true,
        unique: true,
    },
    email: {
        type: String,
        required: true,
        index: true,
        unique: true
    },
    password: {
        type: String,
        required: true,
    },
    ....
});

However, after restarting both my server and mongo session, I can still create users with the same Username and the same Email. I can do this from both the mongo shell and the front-end user registration page.

Is there a second part to this that I'm missing? I'm not for sure how to properly enforce the unique type at this point. Thanks!

jblew
  • 274
  • 1
  • 8
  • 21

2 Answers2

16

Try deleting the database and running your program again, this is maybe because you add the constraint after the database creation and mongoose no recreate the index.

if you cannot delete you database try this in the mongo console

db.users.createIndex({username:1}, {unique:true})

see mongo unique index for more information

stalin
  • 3,442
  • 2
  • 25
  • 25
  • 1
    I deleted my database and then created some new users and the `unique` type worked, thank you! How should I go about handling the error returned if a user tries to make an account with a username already in use? – jblew Feb 18 '18 at 22:28
3

You can also reindex your database in case you don't want to delete it.

mongo <db-name> db.<collection-name>.reIndex()

LuisPinto
  • 1,667
  • 1
  • 17
  • 36