node.js - E11000 mongodb mongoose 中的重复键错误索引

标签 node.js mongodb mongoose

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

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;

这就是我在 Controller 中使用它的方式 -

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 中有条目,它也会引发错误“重复”错误

最佳答案

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

相关文档:

If a document does not have a value for the indexed field in a unique index, the index will store a null value for this document. Because of the unique constraint, MongoDB will only permit one document that lacks the indexed field. 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 combine the unique constraint with the sparse index to filter these null values from the unique index and avoid the error.

unique indexes

Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value.

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

sparse indexes


来自评论:

您的错误表明 key 被命名为 mydb.users.$email_1这让我怀疑您在 users.email 上都有索引和 users.local.email (前者目前已旧且未使用)。从 Mongoose 模型中删除字段不会影响数据库。联系 mydb.users.getIndexes()如果是这种情况,请使用 mydb.users.dropIndex(<name>) 手动删除不需要的索引.

关于node.js - E11000 mongodb mongoose 中的重复键错误索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24430220/

相关文章:

Node.js 初学者 - 无法通过 Nodetuts 教程 2 - 标准输出和子进程

javascript - Node.js REPL 在函数声明或函数表达式后自动声明下划线?

node.js - nginx 反向代理设置在执行 CORS 请求时不保留 session ID

mongodb - 使用logstash elasticsearch的mongodb输入插件

mongodb - mongodb、couchdb在单节点上是否一致?

node.js - 使用 mongoose 连接到 MongoDb - 错误 : getaddrinfo ENOTFOUND

node.js - Adobe Brackets 的 Node.js 调试器也有断点选项吗?

javascript - Mongoose 或 Query 不返回任何内容

node.js - Mongoose .save 不是一个函数

mongodb - 如何在 node.js 中将数据转换为 utf-8?