how to make a variable a unique key in mongoose?

后端 未结 2 1955
春和景丽
春和景丽 2021-02-20 05:13

For example if I have this schema

var userSchema = mongoose.Schema({
    username: String,
    email: String,
    password         


        
2条回答
  •  心在旅途
    2021-02-20 05:46

    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.

提交回复
热议问题