Javascript MongoError,err:E11000 重复键错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13454178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:08:17  来源:igfitidea点击:

MongoError,err:E11000 duplicate key error

javascriptnode.jsmongodbmongoose

提问by dany

I have a MongoDb schema like this

我有一个这样的 MongoDb 模式

    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 ODMAnd this is the code for creating:

我正在尝试创建一个新用户 这是在 NodeJs 中使用 mongoose ODM 完成的,这是用于创建的代码:

    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": "[email protected]",
"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??

我知道这个错误是因为用户名重复,但我没有设置用户名具有唯一约束。每当我添加新行时,我只需要电子邮件是唯一的,用户名可以重复。如何实现?

采纳答案by rdrey

@ManseUK Is probably right, that looks like UserName is a 'key' - in this case an index. The _idattribute is the "primary" index that is created by default, but mongodb allows you to have multiple of these.

@ManseUK 可能是对的,看起来 UserName 是一个“键”——在这种情况下是一个索引。该_id属性是默认创建的“主要”索引,但 mongodb 允许您拥有多个这些索引。

Start a mongo console and run medinfo.users.getIndexes()? Something must have added an index on 'UserName'.

启动 mongo 控制台并运行medinfo.users.getIndexes()? 某些东西必须在“用户名”上添加了索引。

required: truewouldn't do that, but you might have played with other settings previously and the index hasn't been removed?

required: true不会那样做,但是您之前可能已经使用过其他设置并且索引没有被删除?

回答by Claude COULOMBE

There should be an index that is blocking.

应该有一个阻塞的索引。

You can try the db.collection.dropIndex() method

你可以试试 db.collection.dropIndex() 方法

medinfo.users.dropIndexes()

medinfo.users.dropIndexes()

回答by wenqing yu

I got the similar issue on my project. I tried to clear out all the documents and the dup issue still keep popping up. Until I dropped this collection and re-start my node service, it just worked.

我在我的项目中遇到了类似的问题。我试图清除所有文件,但重复问题仍然不断出现。直到我删除这个集合并重新启动我的节点服务,它才起作用。

回答by Cody

What I had realized is that my data-structures were changing -- this is where versioningcomes in handy.

我意识到我的数据结构正在发生变化——这就是versioning派上用场的地方。

You may need to get a mongoose-versionmodule, do a thing.remove({}, ...)or even drop the collection: drop database with mongoose

您可能需要获取一个mongoose-version模块,执行thing.remove({}, ...)甚至删除该集合:使用 mongoose 删除数据库

I use RoboMongo for an admin tool (and I highly recommend it!) so I just went in and right-clicked/dropped collection from the console.

我使用 RoboMongo 作为管理工具(我强烈推荐它!)所以我刚刚进入并从控制台右键单击/删除集合。

If anyone knows how to easily version and/or drop a collection from within the code, feel free to post a comment below as it surely helps this thread ( and I :) ).

如果有人知道如何轻松地从代码中版本和/或删除集合,请随时在下面发表评论,因为它肯定会帮助这个线程(和我 :))。

回答by Abhishek Kumar

The reason behind this error is that,The index is not present or different in your collection, in which you are trying insert. So Solution is to drop that collection and run your program again.

此错误背后的原因是,您尝试插入的集合中的索引不存在或不同。所以解决方案是删除该集合并再次运行您的程序。