30

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??

dany
  • 1,801
  • 7
  • 27
  • 40
  • Perhaps its using the first column as a primary key ? – Manse Nov 19 '12 at 12:50
  • It was a pure guess - im more interested in the question rather than being an expert in the subject - sorry – Manse Nov 19 '12 at 13:01
  • 1
    I don't think so, the previous object having same UserName has an "_id" attribute,which I believe is the primary key .Like this `{ "UserName": "ann", "Email": "ann@f.com", "UserType": "normaluser", "Password":"123456" "_id": "5056d1c7e71c8a0c150003b3" }` – dany Nov 19 '12 at 13:01

4 Answers4

28

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

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

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

rdrey
  • 9,379
  • 4
  • 40
  • 52
  • 3
    Yes, an index was created on users(collection),I listed the indexes on users using `medinfo.users.getIndexes()` and removed the index on UserName. That solved the issue. – dany Nov 20 '12 at 10:53
  • You can also do this in the mongoDB compass app by going to your collection and click on the "indexes" tab. From there you can trash the field you want to avoid this error. – Tony Nov 11 '21 at 14:13
11

There should be an index that is blocking.

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

medinfo.users.dropIndexes()

Claude COULOMBE
  • 3,434
  • 2
  • 36
  • 39
1

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.

wenqing yu
  • 59
  • 1
  • 4
0

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

You may need to get a mongoose-version module, do a thing.remove({}, ...) or even drop the collection: drop database with 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.

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 :) ).

Community
  • 1
  • 1
Cody
  • 9,785
  • 4
  • 61
  • 46