Reputation: 15
My database schema is
var Account = new Schema({
email : String,
name : String ,
family : String ,
password : String
});
I want to use email and password for authentication with passport. my code is:
var LocalStrategy = require('passport-local').Strategy;
passport.use('register', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback : true
},
function(req, email, password, done) {
Account.findOne({ 'email' : email }, function(err, user) {
if (err)
{
return done(err);
}
else
{
var newaccount = new Account();
newaccount.password = bcrypt.hashSync(req.body.password);
newaccount.email = req.body.email;
newaccount.name = req.body.name;
newaccount.family = req.body.family;
// save the user
newaccount.save(function(err) {
if (err)
{
console.log('Error in Saving user: '+err);
throw err;
}
}
});
Although I don't have any username field in
MongoError: E11000 duplicate key error index: Account.accounts.$username_1 dup key: { : null }
The first time I can insert in database and I don't have any error but for second time I have this error that I think it assumes username as key and in first time it sets username as null so for second time that it want to try to set username as null throw error because of duplicate key. I search the internet a lot . I drop the database and I use db.Account.dropIndexes()
but the problem was not solved.
Upvotes: 1
Views: 4456
Reputation: 773
The error message is because a record with null as the username is already present. You have a username feild with the null value.Mongo will only permit one indexed feild with the null value.If there is more than one document without a value for the indexed field or is missing the indexed field, the index build will fail with a duplicate key error.You can use sparse index.
Just remove the null document.
Check with mydb.users.getIndexes() You can manually remove the unwanted index with mydb.users.dropIndex()
Upvotes: 2