【问题标题】:MongoError: E11000 duplicate key error indexMongoError: E11000 重复键错误索引
【发布时间】:2017-03-02 18:55:48
【问题描述】:

我的数据库架构是

var Account = new Schema({
    email : String,
    name : String ,
   family : String ,
   password : String
   });

我想使用电子邮件和密码进行护照身份验证。我的代码是:

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;
                    }
               }
        });

虽然我在

中没有任何用户名字段
MongoError: E11000 duplicate key error index: Account.accounts.$username_1       dup key: { : null }

我第一次可以插入数据库并且我没有任何错误但是第二次我有这个错误我认为它假设用户名作为键并且第一次它将用户名设置为空所以第二次它由于重复键,想尝试将用户名设置为空抛出错误。我在互联网上搜索了很多。我删除了数据库并使用了db.Account.dropIndexes(),但问题没有解决。

【问题讨论】:

标签: node.js mongodb express mongoose passport.js


【解决方案1】:

错误消息是因为用户名为 null 的记录已经存在。您的用户名字段为空值。Mongo 将只允许一个索引字段为空值。如果有多个文档没有索引字段的值或缺少索引字段,则索引构建将失败并显示重复键错误。您可以使用稀疏索引。

只需删除空文档。

使用 mydb.users.getIndexes() 检查您可以使用 mydb.users.dropIndex() 手动删除不需要的索引

【讨论】:

    猜你喜欢
    • 2017-08-27
    • 2017-05-25
    • 2021-09-19
    • 2021-03-04
    • 2019-07-11
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    相关资源
    最近更新 更多