问题描述
为什么我会收到这个重复的错误 - 创建新用户时出错:WriteError({code:11000,index:0,errmsg:insertDocument :: caused by :: 11000 E11000重复键错误索引
?
所有提供的字段根本不为空。
模式:
//声明模式
var userSchema = new mongoose.Schema({
用户名:{type:String,required:true,index:{unique:true}},
password:{type:String,required:true},
created_on:{type:Date,default:Date
发布:
//创建 - POST
//创建API的第一个方法:POST用于创建新用户
router.post( /,function(req,res,next){
//从POST请求获取值
var username = req.body.username;
var password = req.body.password;
console.log(req.body); // {username:'tealou',password:'test123'}
//创建新用户文档
User.create({
username:username,
password:password
},function(err,user){
console.log ); // undefined
if(err){
console.log(创建新用户时出错+ err);
res.send(创建新用户时出错);
} else {
console.log(POST create new user:+ username);
res.json(user);
}
})
});
错误:
任何想法?
解决方案您最初有一个名为 name $您的模式中的c $ c>,设置为唯一
。
我如何知道?因为错误告诉我:
重复键错误索引:** iotdb.users $ name_1 **
您将该字段重命名为 username
,但没有删除旧的索引。默认情况下,MongoDB会将不存在的字段的值设置为 null
。
相关文档:
为了解决这个问题,你需要删除索引为名称
字段。
Why do I get this duplicate error - Error creating new user: WriteError({"code":11000,"index":0,"errmsg":"insertDocument :: caused by :: 11000 E11000 duplicate key error index
?
All the provided fields are not empty at all.
Schema:
// Declare schema
var userSchema = new mongoose.Schema({
username: {type: String, required: true, index: {unique: true}},
password: {type: String, required: true},
created_on: {type: Date, default: Date.now}
});
Post:
// Create - POST
// Create the first method of the API : POST used to create a new user.
router.post("/", function(req, res, next) {
// Get values from POST request
var username = req.body.username;
var password = req.body.password;
console.log(req.body); // { username: 'tealou', password: 'test123' }
// Create new user document
User.create({
username: username,
password: password
}, function(err, user) {
console.log(user); // undefined
if (err) {
console.log("Error creating new user: " + err);
res.send("Error creating new user.");
} else {
console.log("POST creating new user: " + username);
res.json(user);
}
})
});
Error:
any ideas?
解决方案 You initially had a field called name
in your schema, that was set to unique
.
How do I know? Because of the error telling me so:
duplicate key error index: **iotdb.users.$name_1**
You renamed the field to username
, but didn't remove the old index. By default, MongoDB will set the value of a non-existent field to null
in that case.
Relevant documentation here:
To solve this, you need to remove the index for the renamed name
field.
这篇关于Mongoose - 引起的:: 11000 E11000重复键错误索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!