以下是我的 user
模式中的 user.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.email
和 req.body.password
正在获取值。
我也检查了这篇文章,但没有帮助 堆栈链接
如果我完全删除,那么它会插入文档,否则即使我在 local.email 中有一个条目,它也会抛出错误“重复”错误
原文由 Trialcoder 发布,翻译遵循 CC BY-SA 4.0 许可协议
错误消息是说已经有一条以
null
作为电子邮件的记录。换句话说,您已经有一个没有电子邮件地址的用户。相关文档:
唯一索引
换句话说,稀疏索引适用于多个文档都具有
null
值。稀疏索引
来自评论:
您的错误表明密钥被命名为
mydb.users.$email_1
这让我怀疑您在users.email
和users.local.email
上都有索引(前者是旧的和未使用的片刻)。从 Mongoose 模型中删除字段不会影响数据库。如果是这种情况,请使用mydb.users.getIndexes()
检查并使用mydb.users.dropIndex(<name>)
手动删除不需要的索引。