Код ошибки 11000

Доброй ночи, не могу отловить баг. Создаю юзера, но получаю ошибку :

{
    "name": "MongoError",
    "message": "E11000 duplicate key error collection: Udemy.users index: UserSchema.email_1 dup key: { : null }",
    "driver": true,
    "index": 0,
    "code": 11000,
    "errmsg": "E11000 duplicate key error collection: Udemy.users index: UserSchema.email_1 dup key: { : null }"
}

Код : User.js

const mongoose = require('mongoose');
const validator = require('validator');
const jwt = require('jsonwebtoken');
const _ = require('lodash');
 
 
let UserSchema = new mongoose.Schema({
 email: {
  type: String,
  required: true,
  trim: true,
  minlength: 1,
  unique: true,
  validate: {
   validator: validator.isEmail,
   message: '{VALUE} is not a valid email'
  }
 },
 password: {
  type: String,
  require: true,
  minlength: 6
 },
 tokens: [{
  access: {
   type: String,
   required: true
  },
  token: {
   type: String,
   required: true
  }
 }]
});
 
 
UserSchema.methods.toJSON = function () {
 let user = this;
 let userObject = user.toObject();
 
 return _.pick(userObject, ['_id', 'email']);
};
 
 
UserSchema.methods.generateAuthToken = function () {
 let user = this;
 let access = 'auth';
 let token = jwt.sign({_id: user._id.toHexString(), access}, 'abc123').toString();
 user.tokens = user.tokens.concat([{access, token}]);
 return user.save().then(() => {
  return token;
 });
};
 
let User = mongoose.model('User', UserSchema);
 
module.exports = {
 User
};

server.js :

app.post('/users', (req, res) => {
 let body = _.pick(req.body, ['email', 'password']);
 let user = new User(body);
 
 user.save().then(() => {
  return user.generateAuthToken();
 }).then((token) => {
  res.header('x-auth', token).send(user);
 }).catch((e) => {
  res.status(400).send(e);
 })
});

Полный код тут

Спасибо!

Following is my user schema in user.js model —

var userSchema = new mongoose.Schema({
    local: {
        name: { type: String },
        email : { type: String, require: true, unique: true },
        password: { type: String, require:true },
    },
    facebook: {
        id           : { type: String },
        token        : { type: String },
        email        : { type: String },
        name         : { type: String }
    }
});

var User = mongoose.model('User',userSchema);

module.exports = User;

This is how I am using it in my controller —

var user = require('./../models/user.js');

This is how I am saving it in the db —

user({'local.email' : req.body.email, 'local.password' : req.body.password}).save(function(err, result){
    if(err)
        res.send(err);
    else {
        console.log(result);
        req.session.user = result;
        res.send({"code":200,"message":"Record inserted successfully"});
    }
});

Error

{"name":"MongoError","code":11000,"err":"insertDocument :: caused by :: 11000 E11000 duplicate key error index: mydb.users.$email_1  dup key: { : null }"} 

I checked the db collection and no such duplicate entry exists, let me know what I am doing wrong ?

FYI — req.body.email and req.body.password are fetching values.

I also checked this post but no help STACK LINK

If I removed completely then it inserts the document, otherwise it throws error «Duplicate» error even I have an entry in the local.email

Application and websites generate too much data even in a single transaction.

How can we handle this huge amount of data efficiently?

Thanks to the NoSQL capabilities of MongoDB, it makes websites scalable and offers superior performance.

However, the MongoDB error code 11000 can happen due to duplicate entries or bad syntax.

At Bobcares, we often get requests from our customers to fix MongoDB error code 11000 as part of our Server Migration Services.

Today, let’s see how our Migration Engineers fix MongoDB error code 11000.

How we fixed MongoDB error code 11000

At Bobcares, where we have more than a decade of expertise in managing servers, we see many customers face problems while managing MongoDB database.

Now let’s see the major reasons for MongoDB errors and how our Support Engineers fix the top errors.

1. Wrong syntax

Recently, one of our customers wanted to recover data from a MySQL database and transform it into JSON for integration into the MongoDB database.

When it was a single insertion it worked fine. But while doing 45000 insertion, it did not work and resulted in the error:

(node:31032) UnhandledPromiseRejectionWarning: WriteError({"code":11000,"index":0,"errmsg":"E11000 duplicate key error collection: meteor.depart index: _id_ dup key: { : ObjectId('5b1527ee6161057938e0aef0') }","op":{"jourExpl
oitation":::::,"_id":"5b1527ee6161057938e0aef0"}})

On checking our MongoDB Experts found that the problem happened due to syntax error.

When using insertMany, we should use the forceServerObjectId flag. Therefore, we suggested the customer to use the following code to solve the problem.

manyInsert.insertMany(dataJsonInsert, { forceServerObjectId: true }); 

This fixed the problem.

2. Duplicate record

Similarly, another customer had an  E11000 duplicate key error index in MongoDB mongoose. The error said

Error creating new user: WriteError({"code":11000,"index":0,"errmsg":"insertDocument :: caused by :: 11000 E11000 duplicate key error index

On checking the schema, we found that the customer renamed the field to username, but didn’t remove the old index. By default, MongoDB will set the value of a non-existent field to null in that case.

If a document does not have a value for the indexed field in a unique index, the index for this document will store a null value.

Due to the unique condition, MongoDB will only allow one document lacking the indexed field. Also, If there is more than one document without a value for the indexed field or is missing the indexed field, the index execution will fail and results in a duplicate key error.

So, our Support Engineers removed the index for the renamed name field and solved the error.

[Need assistance to fix MongoDB error code 11000? We’ll help you.]

Conclusion

In short, the MongoDB error code 11000 may happen when a document does not have a value for the indexed field or due to the wrong syntax used. Today, we saw the various reasons for MongoDB errors and how our Support Engineers fix them.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

The code 11001 does not exist in the 2.5/2.6 branch on GitHub, so if you’re trying a 2.5 version than you can’t create it. I did have a look at the code, but I can’t find any path that shows the 11001 code either directly.

The following few lines will show code 11001:

db.so.drop();
db.so.insert( { foo: 5 } );
db.so.ensureIndex( { foo: 1 }, { unique: true } );
db.so.insert( { foo: 6 } );

The expected 11000:

db.so.insert( { foo: 5 } );
E11000 duplicate key error index: test.so.$foo_1  dup key: { : 5.0 }

And now to reach the 11001:

db.so.insert( { foo: 6 } );
db.so.update( { foo: 6 }, { $set: { foo: 5 } } );
E11000 duplicate key error index: test.so.$foo_1  dup key: { : 5.0 }

Still the original 11000, but:

db.getPrevError();
{
    "err" : "E11000 duplicate key error index: test.so.$foo_1  dup key: { : 5.0 }",
    "code" : 11001,
    "n" : 0,
    "nPrev" : 1,
    "ok" : 1
}

That the original textual error message shows E11000 is a bug: https://jira.mongodb.org/browse/SERVER-5978

MongoDB Command insert failed: E11000 duplicate key error collection

Today in this article we shall see how to resolve the error E11000 duplicate key error collection in the MongoDB command execution.

Today in this article, we will cover below aspects,

  • Issue Description
  • Resolution

Issue Description

Mongo Insert/Update operation gives the below error,

MongoDB.Driver.MongoComamndException: Command insert failed: E11000 duplicate key error collection:[yourccollection] index :[key] dup key: { : }

Resolution

I had this error recently for Upsert operation,

var returnDoc = await collectionnew.FindOneAndUpdateAsync<Library>(
                   filter: Builders<Library>.Filter.Eq("_id", userId),
                   update: update.Combine(updates),
                   options: new FindOneAndUpdateOptions<Library, Library>
                   {
                       IsUpsert = true,
                       ReturnDocument = ReturnDocument.After,
                   });
 
               if(returnDoc!=null)
               {
                   //your logic here
               }
  • E11000 duplicate key error could occur due to many factors depending on the type of operation you are performing.
  • This error however indicates that the issue has occurred because the key with which you performed the Mongo operation key already exists with the value specified.
  • This also meant the indexed key in the error is a unique key and not the non-unique key or sparsed key. That means only one key with a unique value can exist in the given mongo collection.

Generally, you will have default _id as a unique key in the mongo collection.

Example:

Create MongoDB compound indexes

But you can add more unique keys depending on your requirements provided you are 100% sure, its value will remain unique for the whole collection and won’t conflict with other ids.

To fix the issue, please try any of the below guidelines,

  • Do you need the indexed field to be unique really? If not, then create an index with the non-unique index or sparsed index, etc.

Example:

How to create MongoDB indexes using UI

Above, we have used a non-unique index since the data field can have duplicates and ideally can not remain unique logically.

  • Delete unnecessary index – Don’t use indexed if not necessary – MongoDB Indexing Guidelines and Best Practices
  • Apply unique index to only those fields which will have values. For example, if the value is not specified then it’s possible mongo assigns the null value, then a null value will be assigned to the very first record but the second record will throw the duplicate error issue.

Please make sure the indexed fields are properly indexed. If you are 100% sure of the index field will remain unique across the collection then only you can make it a unique indexed field else make it indexed but non-unique so that duplicated values can be allowed. Using this option also meant that you already have _id or any other unique id to be used for the query considering the performance.

References:

  • MongoDB Indexing Guidelines and Best Practices
  • MongoDB Collection Naming Convention

That’s all! Happy coding!

Does this help you fix your issue?

Do you have any better solutions or suggestions? Please sound off your comments below.


Please bookmark this page and share it with your friends. Please Subscribe to the blog to get a notification on freshly published best practices and guidelines for software design and development.


Are you sure you’re dropping the right database? Make sure you do use dbName; db.dropDatabase();.

Yes, I switched to dbName before dropping the database

The insert code is straightforward:

db.collection('users', function (err, collection) {
  collection.insert(contacts, function(err, result) {
    if (err) {
      job.log('Failed to save contacts as user with error: ' + JSON.stringify(err));
      done('Failed to save contacts as user with error: ' + JSON.stringify(err));
    } else {
      console.log(result.length);
      done();
    }
  });
});

contacts is an array of json in accordance with the users' schema whose schema is defined such that no unique index exists.

I have about 760 records out of which about 93 are inserted without any issues, the processing stops at 94th entry. This is what the 94th entry looks like:

{
    "phone": [
        {
            "number": "91xxxxxxxxxxx",
            "numberType": "work",
            "contactReferrer": "546a20a7a8b0aaf0175f3ae1"
        },
        {
            "number": "91yyyyyyyyyyy",
            "numberType": "home",
            "contactReferrer": "546a20a7a8b0aaf0175f3ae1"
        },
        {
            "number": "91zzzzzzzzzzz",
            "numberType": "work",
            "contactReferrer": "546a20a7a8b0aaf0175f3ae1"
        }
    ],
    "organization": [
        {
            "organization": "the org",
            "title": null,
            "employmentType": "employment"
        }
    ],
    "email": [
        {
            "emailId": "xxx@gmail.com",
            "emailType": "other",
            "contactReferrer": "546a20a7a8b0aaf0175f3ae1"
        }
    ],
    "address": [
        {
            "state": "Karnataka",
            "postalCode": null,
            "addressType": "other",
            "poBox": null,
            "street": null,
            "city": "Bidar",
            "country": "India"
        },
        {
            "state": "Karnataka",
            "postalCode": null,
            "addressType": "other",
            "poBox": null,
            "street": null,
            "city": "Bidar",
            "country": "India"
        }
    ],
    "name": [
        {
            "firstName": "Rakesh",
            "lastName": "Raman",
            "contactReferrer": "546a20a7a8b0aaf0175f3ae1"
        }
    ],
    "_id": "546a2786044e2cd928698eb0"
}

The error:

{"code":11000,"index":109,"errmsg":"insertDocument :: caused by :: 11000 E11000 duplicate key error index: dbName.users.$_id_ dup key: { : ObjectId('546a2786044e2cd928698eb0') }

I have setup a replica set and want to add it in a mongos. But I got below error in mongos:

mongos> sh.addShard("rs3/172.19.0.12:27017,172.19.0.6:27017,172.19.0.5:27017")
{
    "code" : 11000,
    "ok" : 0,
    "errmsg" : "E11000 duplicate key error collection: admin.system.version index: _id_ dup key: { : "shardIdentity" }"
}

from the above message, it says admin.system.version has duplicate key error. The collection admin.system.version should be set by mongodb. I don’t understand why it has a duplicate key.

All mongo instances are 3.4.4 version.

Below is the replica set status:

rs3:PRIMARY> rs.status()
{
    "set" : "rs3",
    "date" : ISODate("2017-07-09T02:13:37.146Z"),
    "myState" : 1,
    "term" : NumberLong(10),
    "heartbeatIntervalMillis" : NumberLong(2000),
    "optimes" : {
        "lastCommittedOpTime" : {
            "ts" : Timestamp(0, 0),
            "t" : NumberLong(-1)
        },
        "appliedOpTime" : {
            "ts" : Timestamp(1499566407, 1),
            "t" : NumberLong(10)
        },
        "durableOpTime" : {
            "ts" : Timestamp(1499563905, 1),
            "t" : NumberLong(9)
        }
    },
    "members" : [
        {
            "_id" : 0,
            "name" : "172.19.0.12:27017",
            "health" : 1,
            "state" : 1,
            "stateStr" : "PRIMARY",
            "uptime" : 2493,
            "optime" : {
                "ts" : Timestamp(1499566407, 1),
                "t" : NumberLong(10)
            },
            "optimeDate" : ISODate("2017-07-09T02:13:27Z"),
            "electionTime" : Timestamp(1499563936, 1),
            "electionDate" : ISODate("2017-07-09T01:32:16Z"),
            "configVersion" : 414750,
            "self" : true
        },
        {
            "_id" : 1,
            "name" : "172.19.0.5:27017",
            "health" : 1,
            "state" : 2,
            "stateStr" : "SECONDARY",
            "uptime" : 1403,
            "optime" : {
                "ts" : Timestamp(1499566407, 1),
                "t" : NumberLong(10)
            },
            "optimeDurable" : {
                "ts" : Timestamp(1499563905, 1),
                "t" : NumberLong(9)
            },
            "optimeDate" : ISODate("2017-07-09T02:13:27Z"),
            "optimeDurableDate" : ISODate("2017-07-09T01:31:45Z"),
            "lastHeartbeat" : ISODate("2017-07-09T02:13:35.870Z"),
            "lastHeartbeatRecv" : ISODate("2017-07-09T02:13:35.854Z"),
            "pingMs" : NumberLong(0),
            "syncingTo" : "172.19.0.12:27017",
            "configVersion" : 414750
        },
        {
            "_id" : 2,
            "name" : "172.19.0.6:27017",
            "health" : 1,
            "state" : 3,
            "stateStr" : "RECOVERING",
            "uptime" : 2487,
            "optime" : {
                "ts" : Timestamp(1499070510, 1000),
                "t" : NumberLong(3)
            },
            "optimeDurable" : {
                "ts" : Timestamp(1499070510, 1000),
                "t" : NumberLong(3)
            },
            "optimeDate" : ISODate("2017-07-03T08:28:30Z"),
            "optimeDurableDate" : ISODate("2017-07-03T08:28:30Z"),
            "lastHeartbeat" : ISODate("2017-07-09T02:13:35.865Z"),
            "lastHeartbeatRecv" : ISODate("2017-07-09T02:13:36.965Z"),
            "pingMs" : NumberLong(0),
            "configVersion" : 414750
        }
    ],
    "ok" : 1
}

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.

The corresponding judgment can be made in err.

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

ღ( ´・ᴗ・` )❤ End.

Описание проблемы:

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)]: {} 

причина:

Поскольку в схеме установлено unique: true, зарегистрированное имя пользователя должно быть уникальным.

Соответствующее суждение можно сделать с ошибкой.

if(err.code == '11000'){
    res.json({
        msg: 'Имя пользователя уже зарегистрировано, измените имя пользователя',
        success:false
    })
}

ღ (´ ・ ᴗ ・ `) ❤ закончено.

Понравилась статья? Поделить с друзьями:
  • Код ошибки 110 что это
  • Код ошибки 110 самсунг телевизор
  • Код ошибки 110 роблокс
  • Код ошибки 110 проверьте общие настройки криптографии
  • Код ошибки 1127 тойота