小编典典

E11000 MongoDB mongoose中的重复键错误索引

node.js

以下是我useruser.js模型中的架构-

var userSchema = new mongoose.Schema({
    local: {
        name: { type: String },
        email : { type: String, require: true, unique: true },
        password: { type: String, require:true },
    },
    facebook: {
        id           : { type: String },
        token        : { type: String },
        email        : { type: String },
        name         : { type: String }
    }
});

var User = mongoose.model('User',userSchema);

module.exports = User;

这就是我在控制器中使用它的方式-

var user = require('./../models/user.js');

这就是我将其保存在数据库中的方式-

user({'local.email' : req.body.email, 'local.password' : req.body.password}).save(function(err, result){
    if(err)
        res.send(err);
    else {
        console.log(result);
        req.session.user = result;
        res.send({"code":200,"message":"Record inserted successfully"});
    }
});

错误 -

{"name":"MongoError","code":11000,"err":"insertDocument :: caused by :: 11000 E11000 duplicate key error index: mydb.users.$email_1  dup key: { : null }"}

我检查了数据库集合,没有这样的重复条目,让我知道我在做什么错吗?

仅供参考- req.body.emailreq.body.password被获取的值。

我也检查了这篇文章,但没有帮助STACK
LINK

如果我将其完全删除,则它将插入文档,否则即使我在local.email中有条目,也会引发错误“ Duplicate”错误


阅读 332

收藏
2020-07-07

共1个答案

小编典典

错误消息是说已经有一条记录null作为电子邮件。换句话说,您已经有一个没有电子邮件地址的用户。

相关文档:

如果文档在唯一索引中没有索引字段的值,则索引将为此文档存储一个空值。由于存在独特的约束,MongoDB将只允许一个缺少索引字段的文档。如果有多个文档没有索引字段的值,或者缺少索引字段,则索引构建将失败,并出现重复的键错误。

您可以将唯一性约束与稀疏索引结合使用,以从唯一性索引中过滤这些空值并避免错误。

唯一索引

稀疏索引仅包含具有索引字段的文档条目,即使索引字段包含空值也是如此。

换句话说,对于多个都具有null值的文档,稀疏索引是可以的。

稀疏索引


来自评论:

您的错误表明该键已命名mydb.users.$email_1,这使我怀疑您在users.email和上都有一个索引users.local.email(当前该键旧且未使用)。从猫鼬模型中删除字段不会影响数据库。检查mydb.users.getIndexes()是否存在这种情况,并使用手动删除不需要的索引mydb.users.dropIndex(<name>)

2020-07-07