E11000 duplicate key error index in mongodb mongoose

前端 未结 25 1636
自闭症患者
自闭症患者 2020-11-22 05:49

Following is my user schema in user.js model -

var userSchema = new mongoose.Schema({
    local: {
        name: { type: String },
         


        
25条回答
  •  花落未央
    2020-11-22 06:31

    This is my relavant experience:

    In 'User' schema, I set 'name' as unique key and then ran some execution, which I think had set up the database structure.

    Then I changed the unique key as 'username', and no longer passed 'name' value when I saved data to database. So the mongodb may automatically set the 'name' value of new record as null which is duplicate key. I tried the set 'name' key as not unique key {name: {unique: false, type: String}} in 'User' schema in order to override original setting. However, it did not work.

    At last, I made my own solution:

    Just set a random key value that will not likely be duplicate to 'name' key when you save your data record. Simply Math method '' + Math.random() + Math.random() makes a random string.

提交回复
热议问题