E11000 duplicate key error index in mongodb mongoo

2018-12-31 22:06发布

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

17条回答
情到深处是孤独
2楼-- · 2018-12-31 22:27

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.

查看更多
一个人的天荒地老
3楼-- · 2018-12-31 22:29

This happens when there are frequent schema indexes and changes in a current database and this can be easily fixed by deleting the system indexes and the whole collection.

It Works after doing that, this also happens when there's no unique key to separate two documents from each other.

If you're using a shell, then you can drop the db via -

db.users.drop();

I Hope this helped :)

查看更多
看风景的人
4楼-- · 2018-12-31 22:29

I faced similar issues , I Just clear the Indexes of particular fields then its works for me . https://docs.mongodb.com/v3.2/reference/method/db.collection.dropIndexes/

查看更多
明月照影归
5楼-- · 2018-12-31 22:29

I want to explain the answer/solution to this like I am explaining to a 5-year-old , so everyone can understand .

I have an app.I want people to register with their email,password and phone number . In my MongoDB database , I want to identify people uniquely based on both their phone numbers and email - so this means that both the phone number and the email must be unique for every person.

However , there is a problem : I have realized that everyone has a phonenumber but not everyone has an email address .

Those that don`t have an email address have promised me that they will have an email address by next week. But I want them registered anyway - so I tell them to proceed registering their phonenumbers as they leave the email-input-field empty .

They do so .

My database NEEDS an unique email address field - but I have a lot of people with 'null' as their email address . So I go to my code and tell my database schema to allow empty/null email address fields which I will later fill in with email unique addresses when the people who promised to add their emails to their profiles next week .

So its now a win-win for everyone (but you ;-] ): the people register, I am happy to have their data ...and my database is happy because it is being used nicely ...but what about you ? I am yet to give you the code that made the schema .

Here is the code : NOTE : The sparse property in email , is what tells my database to allow null values which will later be filled with unique values .

var userSchema = new mongoose.Schema({
  local: {
    name: { type: String },
    email : { type: String, require: true, index:true, unique:true,sparse: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;

I hope I have explained it nicely . Happy NodeJS coding / hacking!

查看更多
刘海飞了
6楼-- · 2018-12-31 22:31

If you are still in your development environment, I would drop the entire db and start over with your new schema.

From the command line

➜ mongo
use dbName;
db.dropDatabase();
exit
查看更多
低头抚发
7楼-- · 2018-12-31 22:31

I had same Issue. Problem was that I have removed one field from model. When I dropped db it fixes

查看更多
登录 后发表回答