mongoose: unique field isn't working
Use this mongoose-unique-validator
var mongoose = require('mongoose');var uniqueValidator = require('mongoose-unique-validator'); // Define your schema as normal.var userSchema = mongoose.Schema({ username: { type: String, required: true, unique: true }, email: { type: String, index: true, unique: true, required: true }, password: { type: String, required: true }}); // Apply the uniqueValidator plugin to userSchema.userSchema.plugin(uniqueValidator);
If you do it like this, It will not work for unique key validation.
var userSchema = new Schema({ name : String, username : { type : String, required : true, index : { unique : true, dropDups : true } });
So you doing it in correct and best way right now, just do it like this
Drop the collection from database using following command
> db.<collection name>.drop()
Then restart server and check by doing in this way.
var userSchema = new Schema({ name : String, username : { type : String, required : true, unique : true });