how to make a variable a unique key in mongoose?

I came across the same issue. But can't be solved by the accepted answer.

For my example is very simple, just make the name unique.

var FoolSchema = Schema({
    name: {
      type: String,
      unique: true,
      index: true,
      required: true
    }
})

I can save the duplicate name every time.

Then I find this link: https://mongoosejs.com/docs/faq.html#unique-doesnt-work

The solution is createIndex from mongoDB, not from mongoose.

  1. start mongo shell mongo, and use yourdbName
  2. run db.foos.getIndexes() (you can't see the "unique" : true, )
  3. db.foos.createIndex( { "name": 1 }, { unique: true } )
  4. try step 2. The results should contains unique.

Hope it could help someone.

EDIT If your foo table collections contain the duplicated names, you might get error on step 3:

{
    "ok" : 0,
    "errmsg" : "E11000 duplicate key error collection: mategoal-dev.categories index: name_1 dup key: { : \"TheName\" }",
    "code" : 11000,
    "codeName" : "DuplicateKey"
}

Then remove all the data or duplicated one(haven't test) first:

db.foos.remove({})

Then try step 3 again.


You can add a constraint with the unique attribute. This will also add a "unique" index for the field to your collection:

var userSchema = mongoose.Schema({
    username: { type: String, unique: true },
    email: String,
    password: String,
    _todo: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Todo'}]
});