MongoError,err:E11000 duplicate key error

前端 未结 5 820
抹茶落季
抹茶落季 2020-12-28 15:40

I have a MongoDb schema like this

    var User = new Schema({
    \"UserName\": { type: String, required: true },
    \"Email\": { type: String, required: tr         


        
相关标签:
5条回答
  • 2020-12-28 15:52

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

    0 讨论(0)
  • 2020-12-28 15:57

    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.

    0 讨论(0)
  • 2020-12-28 16:06

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

    0 讨论(0)
  • 2020-12-28 16:08

    There should be an index that is blocking.

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

    medinfo.users.dropIndexes()

    0 讨论(0)
  • 2020-12-28 16:08

    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.

    0 讨论(0)
提交回复
热议问题