Mongoose Error: e11000 duplicate key error collection, code: 11000

Problem description:

MongoError: E11000 duplicate key error collection: test.elementusers index: username_1 dup key: { username: "admin" }
    at Function.create (/Users/liangrumeng/Documents/HBuilderProjects/workspace/myapp/node_modules/mongodb/lib/core/error.js:44:12)
    at toError (/Users/liangrumeng/Documents/HBuilderProjects/workspace/myapp/node_modules/mongodb/lib/utils.js:150:22)
    at coll.s.topology.insert (/Users/liangrumeng/Documents/HBuilderProjects/workspace/myapp/node_modules/mongodb/lib/operations/common_functions.js:266:39)
    at handler (/Users/liangrumeng/Documents/HBuilderProjects/workspace/myapp/node_modules/mongodb/lib/core/sdam/topology.js:1000:24)
    at wireProtocol.(anonymous function) (/Users/liangrumeng/Documents/HBuilderProjects/workspace/myapp/node_modules/mongodb/lib/core/sdam/server.js:457:5)
    at /Users/liangrumeng/Documents/HBuilderProjects/workspace/myapp/node_modules/mongodb/lib/core/connection/pool.js:408:18
    at process._tickCallback (internal/process/next_tick.js:61:11)
  driver: true,
  name: 'MongoError',
  index: 0,
  code: 11000,
  keyPattern: { username: 1 },
  keyValue: { username: 'admin' },
  errmsg:
   'E11000 duplicate key error collection: test.elementusers index: username_1 dup key: { username: "admin" }',
  [Symbol(mongoErrorContextSymbol)]: {} 

MongoError: E11000 duplicate key error collection: test.elementusers index: username_1 dup key: {username: “admin”}
at Function. Create
driver: true,
name: ‘MongoError’,
index: 0,
code: 11000,
keyPattern: {username: 1},
keyValue: {username: ‘admin’},
errmsg:
‘E11000 duplicate key error collection: Test.elementusers index: username_1 dup key: {username: “admin”}’,
[Symbol(mongoErrorContextSymbol)]: {}
The reason:
Because unique:true is set in the Schema, the registered user name must be unique.

We can make a corresponding judgment in ERR.

if(err.code == '11000'){
    res.json({
        msg:'This username has already been registered, please change your username',
        success:false
    })
}

Read More: