MongoError: E11000 duplicate key error collection with passport

Viewed 2097

I have the following userSchema

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

var userSchema = new mongoose.Schema({
email: String,
password: String,
userName: String,
fname: String,
lname: String,
userType: Number,
subscribedThreads: [
    {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Threads"
    }
]
});
// add passport methods
userSchema.plugin(passportLocalMongoose);
// export modules to be used by the file requiring it
module.exports = mongoose.model("Users",userSchema);

The first entry into the collection occurs as it should but the next ones give

{ [MongoError: E11000 duplicate key error collection: KManV3.users 
index: username_1 dup key: { : null }]
name: 'MongoError',
message: 'E11000 duplicate key error collection: KManV3.users index: 
username_1 dup key: { : null }',
driver: true,
code: 11000,
index: 0,
errmsg: 'E11000 duplicate key error collection: KManV3.users index: 
username_1 dup key: { : null }',
getOperation: [Function],
toJSON: [Function],
toString: [Function] 
}

Also, dbname.users.getIndexes() gives:

> db.users.getIndexes()
[
{
    "v" : 1,
    "key" : {
        "_id" : 1
    },
    "name" : "_id_",
    "ns" : "KManV3.users"
},
{
    "v" : 1,
    "key" : {
        "password" : 1
    },
    "name" : "password_1",
    "ns" : "KManV3.users",
    "background" : true
},
{
    "v" : 1,
    "unique" : true,
    "key" : {
        "username" : 1
    },
    "name" : "username_1",
    "ns" : "KManV3.users",
    "background" : true
}
]

Apparently every property of schema has been set as unique and I can't add data into collections even if the data is totally different. I'm not sure if it's due to integration of passport.

2 Answers

Error reason - The index is not present in your collection, in which you are trying to insert. Solution - drop that collection and run your program again.

Related