Reputation: 47
When I first send data (post), it will be stored, but when I send different data second time, it produces the error message
"error": "E11000 duplicate key error index: mongodb-database.users.$name_1 dup key: { : null }"
But, in my db, there is no null data, which I think it shouldn't be duplicated? I am not sure if there is another code that causes error.
Any ideas help me. Thanks.
My route
.post(function(req, res, next){
Users.create(req.body).then(function(user){
res.json(user);
}).catch(next);
});
My model
var userSchema = new Schema({
name: {
type: String,
// required: [true, "Name field is required"],
unique:true
}
});
My index.html (using Ajax)
$.("form").submit(function(event){
var order = {
name: $username.val(),
};
$.ajax({
type: 'POST',
url: '/users',
data: order
success: function(newOrder){
$result.append('<li>name: ' + newOrder.username + '</li>');
},
error: function(){
alert('error saving order');
}
});
});
});
</script>
</head>
<body>
<div id="result"></div>
<form action="/users" method="POST">
<label>Username:<input type="text" id="username"></label>
<input type="submit" value="Submit" id="post_message">
</form>
Upvotes: 0
Views: 70
Reputation: 1554
This error is occurring due to unique key constraint that you added in model definition. Remove unique from model and add require if you want to make name field required. You can redefine your model like this
var userSchema = new Schema({
name: {
type: String,
// required: [true, "Name field is required"],
required: true
}
});
Upvotes: 1