Код ошибки 11000

I have a MongoDb schema like this

    var User = new Schema({
    "UserName": { type: String, required: true },
    "Email": { type: String, required: true, unique: true },
    "UserType": { type: String },
    "Password": { type: String }
});

I am trying to create a new user
This is done in NodeJs using mongoose ODM
And this is the code for creating:

    controller.createUser = function (req, res) {

    var user = new models.User({
        "UserName": req.body.UserName.toLowerCase(),
        "Email": req.body.Email.toLowerCase(),
        "UserType": req.body.UserType.toLowerCase()
    });
    models.User.findOne({ 'Email': user.Email }, function (err, olduser) {
                    if (!err) {
                        if (olduser) {
                            res.send({ 'statusCode': 409, 'statusText': 'Email Already Exists' });
                        }
                        else if (!olduser) {
                            user.setPassword(req.body.Password);
                            user.save(function (err, done) {
                                if (!err) {
                                    console.log(user);
                                    res.send({ 'statusCode': 201, 'statusText': 'CREATED' });
                                }
                                else {
                                    res.send({ 'Status code': 500, 'statusText': 'Internal Server Error' });
                                }
                            });
                        }
                    }
                    else {
                        res.send({ 'statusCode': 500, 'statusText': 'ERROR' });
                    }
                });
};

The for creating new user,I am giving attributes and values as follows:

 {
"UserName": "ann",
"Email": "ann@ann.com",
"UserType": "normaluser",
"Password":"123456"
}

And I am getting error like this:

{"Status code":500,"statusText":"Internal Server Error","Error":{"name":"MongoError","err":"E11000 duplicate key error index: medinfo.users.$UserName_1  dup key: { : \"ann\" }","code":11000,"n":0,"connectionId":54,"ok":1}}

I understand that this error is because UserName is duplicated ,but I haven’t set UserName with unique constraint.Whenever I add a new row,I need only email to be unique,UserName can be repeated.How to achieve this??

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

{
    "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);
 })
});

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

Спасибо!

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»;

I have a MongoDb schema like this

    var User = new Schema({
    "UserName": { type: String, required: true },
    "Email": { type: String, required: true, unique: true },
    "UserType": { type: String },
    "Password": { type: String }
});

I am trying to create a new user
This is done in NodeJs using mongoose ODM
And this is the code for creating:

    controller.createUser = function (req, res) {

    var user = new models.User({
        "UserName": req.body.UserName.toLowerCase(),
        "Email": req.body.Email.toLowerCase(),
        "UserType": req.body.UserType.toLowerCase()
    });
    models.User.findOne({ 'Email': user.Email }, function (err, olduser) {
                    if (!err) {
                        if (olduser) {
                            res.send({ 'statusCode': 409, 'statusText': 'Email Already Exists' });
                        }
                        else if (!olduser) {
                            user.setPassword(req.body.Password);
                            user.save(function (err, done) {
                                if (!err) {
                                    console.log(user);
                                    res.send({ 'statusCode': 201, 'statusText': 'CREATED' });
                                }
                                else {
                                    res.send({ 'Status code': 500, 'statusText': 'Internal Server Error' });
                                }
                            });
                        }
                    }
                    else {
                        res.send({ 'statusCode': 500, 'statusText': 'ERROR' });
                    }
                });
};

The for creating new user,I am giving attributes and values as follows:

 {
"UserName": "ann",
"Email": "ann@ann.com",
"UserType": "normaluser",
"Password":"123456"
}

And I am getting error like this:

{"Status code":500,"statusText":"Internal Server Error","Error":{"name":"MongoError","err":"E11000 duplicate key error index: medinfo.users.$UserName_1  dup key: { : \"ann\" }","code":11000,"n":0,"connectionId":54,"ok":1}}

I understand that this error is because UserName is duplicated ,but I haven’t set UserName with unique constraint.Whenever I add a new row,I need only email to be unique,UserName can be repeated.How to achieve this??

So, I’m writing an application where a user can create a’trip’ which is basically a set of locations they wish to travel to at a particular time and date and the price they’re charging for every point they wish to travel to.

The only problem is that when I do MongoDBCollectionName.create(data, (err,newTrip)=>{…}), I get the same error (after there’s 1 document in the collection) :

ERROR reported while creating a trip from the driver… { MongoError: E11000 duplicate key error collection: hitchhiqe.trips index: username_1 dup key: { : null }

Now, what I don’t understand is where index : username_1 came from because none of the fields in my mongo document contains username_1.

Really appreciate any help.

I tried the following:

  1. Set sparse to true. But that didn’t do anything.
  2. I’m currently storing data in a global variable (i know it’s a bad programming practice, but it’s necessary for this project because i’m holding data onto multiple post routes before finally saving it).
  3. I thought the global variable might’ve caused some issues (even though console.log(global.data) prints out whole data every-time. So, I stored the new data into a local variable within the Post Route. But it still produces Error: 11000
  4. I’m using res.locals to collect data from current user. So, in the global variable (which is object of objects (see code below)), I’m passing the value for some keys as req.user.username or req.user.birthday. I don’t think this could be the problem as I already set the value for such fields in MongoDB as {unique : false}

  5. I went almost every single post on Stackoverflow and YouTube on Error : 11000 but no matter what I try (I implemented sparsing from one of stackoverflow posts), I still get the same error.

  6. I used mongoose.Promise = global.Promise; But that didn’t do anything (someone in stackoverflow recommended it).

  7. I’m REALLY in need of help. I’ve tried debugging it for days but to no success. My head hurts. THANK You SO MUCH for helping!

HERE’s MY mongoDB Schema — Trip — :

var mongoose = require("mongoose"),
    passportLocalMongoose = require("passport-local-mongoose");

var TripSchema = new mongoose.Schema({
    // Destination and price for each point
    Trip : 
    {
        // Where is the user leaving from (no price, obviously)
        from : 
        {
            destination : String
        },

        //First via point (if applicable)
        A : 
            {
                destination : {type : String, sparse : true},
                price : {type : Number, sparse : true}
            },
        //Second via point (if applicable)
        B : 
            {
                destination : {type : String, sparse : true},
                price : {type : Number, sparse : true}
            },    
        // Final Destination (REQUIRED)
        C : 
            {
                destination : {type: String, sparse : false},
                price : {type : Number, sparse : false}
            }
    },   
    // Leaving date, time, and the number of seats available
    Logistics : 
        {
            date : String, //When the user is leaving
            time : String, // Time the user is leaving
            ejsTimePosted : String, //Time ejs will start hiding the event
            seats : Number, // Number of seats available
            totalDuration : Number,
            totalDistance : Number,
            ejsTimeDeleted : Number //Time to send user an email about trip
        },

    dateCreated : String, //date this ride was made available

    // Information about the user who posted/requested a ride 
    Driver : {
        note : String,
        name : {type : String, unique : false},
        email : {type : String, unique : false},
        phone    : String,
        profilePicture : String,
        sex : String,
        carImages : String,
        car        : String,
        university : String,
        graduationYear : String
    }
});

TripSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Trip", TripSchema);

This is where I get data from a user (this is way before I save anything into the db) :

Here’s the GLOBAL Variable, TripInformation :

global.TripInformation = {
  Trip :
  {
     from : 
     {
      destination : req.body.from.split(",").slice(-3).toString().trim()
     },
     A : 
     {
      destination : first_via_point.trim(),
      price       : req.body.first_via_point_price
     },
     B : 
     {
     destination : second_via_point.trim(),
     price       : req.body.second_via_point_price
     },
     C : 
     {
     destination : req.body.to.split(",").slice(-3).toString().trim(),
     price       : req.body.final_destination_price
     },
     },
     Logistics : 
     {
     date : req.body.leaving_date,
     time : req.body.leaving_time,
     ejsTimePosted : toTimestamp(req.body.leaving_date+", "+ req.body.leaving_time),
     seats : req.body.seats_available,
     totalDistance : parseFloat(tD/1609.344).toFixed(1),
     totalDuration : parseFloat(parseFloat(tS/3600).toFixed(1)),
     ejsTimeDeleted : departureT + tS
     },
    dateCreated : moment().format('MMMM Do YYYY, h:mm:ss a'),
      Driver : {
       note : req.body.note,
       name : req.user.name,
       email : req.user.username,
       phone    : req.user.phone,
       profilePicture : req.user.profilePicture,
      sex : req.user.sex,
       carImages : req.user.Driver.carImages,
        car       : req.user.Driver.car,
       university : req.user.university,
       graduationYear : req.user.graduationYear
   }
};

AS YOU CAN SEE, I stored it in a global variable.

NOTE : toTimeStamp() is a function that converts human readable time into a timestamp (I defined it as a global function)

Now, this is in a different ROUTE.

After this, I’m sending user to a ‘Preview’ route where they can preview the data they inserted. If they confirm, they are taken to CONFIRMATION route where I store in their data into Trip (name of my collection) Document.

Here’s the code :

router.post("/confirm-route", function(req, res){

    Trip.create(global.TripInformation, function(err, newTrip){
        if(err)
        {
            console.log("ERROR reported while creating a trip from the driver...", err);
            return res.redirect("/drive/new");
        }
        else
        {
             console.log(newTrip, 'SUCCESS!!!');

            return res.redirect("/marketplace");
        }

    });
})

Here’s the actual error message :


Everytime there's at least 1 document in the collection, the following error is produced : 

ERROR reported while creating a trip from the driver... { MongoError: E11000 duplicate key error collection: hitchhiqe.trips index: username_1 dup key: { : null }
    at Function.create (C:\Users\qasim\Desktop\Exigence\HItchhiqe\source code\src\node_modules\mongodb-core\lib\error.js:43:12)
    at toError (C:\Users\qasim\Desktop\Exigence\HItchhiqe\source code\src\node_modules\mongodb\lib\utils.js:149:22)
    at coll.s.topology.insert (C:\Users\qasim\Desktop\Exigence\HItchhiqe\source code\src\node_modules\mongodb\lib\operations\collection_ops.js:859:39)
    at C:\Users\qasim\Desktop\Exigence\HItchhiqe\source code\src\node_modules\mongodb-core\lib\connection\pool.js:397:18
    at process._tickCallback (internal/process/next_tick.js:61:11)
  driver: true,
  name: 'MongoError',
  index: 0,
  code: 11000,
  errmsg:
   'E11000 duplicate key error collection: hitchhiqe.trips index: username_1 dup key: { : null }',
  [Symbol(mongoErrorContextSymbol)]: {} }

NOW, the only problem is that the data is completely different, literally everything. Also, I have no idea where username_1 comes from in dup key. I tried refactoring my code but I keep getting the same results. I have used similar techniques in my previous projects (except for global variables because I didn’t need it there) but it works there perfectly.


P.s, this is my first post on stackoverflow. So, if this question seems like a lot, my apologies. I’ll definitely make the next question much shorter, haha.

I really hope you can help me as I’ve tried almost everything and don’t want to give up when I’m so close being done. Thank you so much!!!

Понравилась статья? Поделить с друзьями:
  • Код ошибки 1100 iphone
  • Код ошибки 11001 узел не найден
  • Код ошибки 1101 roblox xbox
  • Код ошибки 110 проверьте общие настройки криптографии
  • Код ошибки 110 на телевизоре самсунг смарт тв