【发布时间】:2018-01-19 14:14:17
【问题描述】:
以下是我在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;
这就是我在控制器中使用它的方式 -
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 正在获取值。
我也查看了这篇文章,但没有帮助STACK LINK
如果我完全删除然后它会插入文档,否则即使我在 local.email 中有一个条目,它也会抛出错误“重复”错误
【问题讨论】:
-
有同样的错误!在开发过程中,我们禁用了自动索引并使用小写模式名称/键。我们后来决定改用 TitleCase,但未能更新我们的索引名称(即:titleCase 而不是 TitleCase)。所以当我们启用索引时,我们得到了这个错误。花了一点时间才弄清楚。您需要确保所有名称/键在任何地方都准确命名。
-
我遇到了同样的错误,将猫鼬模型设置为
unique: false没有任何影响。我意识到我必须先放下桌子,然后它才会起作用。你可以做类似db.whateverthecollection.drop({})的事情。小心,它会删除集合。 -
_id: mongoose.Types.ObjectId 添加,因为需要唯一的 id
-
@Pere 我不相信这行得通,谢谢