node.js - E11000 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>) 手动删除不需要的索引.

https://stackoverflow.com/questions/24430220/

相关文章:

mongodb - 如何监听 MongoDB 集合的变化?

mongodb - 根据日期返回查询

arrays - 如何在 mongodb 中更新多个数组元素

node.js - 比较 Mongoose _id和字符串

javascript - 如何在mongodb中的对象数组中搜索

database - 如何使用mongoimport导入csv

mongodb - 如何为 MongoDB 集合中的所有文档选择单个字段?

mongodb - 对于小型 .NET 应用程序,什么是好的数据库选择?

mongodb - 无法创建/打开锁定文件 :/data/mongod. lock errno:13

mongodb - 如何查询嵌套对象?