Reputation: 87
I have using mongoose promise to catch error when user try to register new user and email. Here is the code:
user.service.js
function create(userParams) {
var user = new User(userParams);
return user.save();
}
and on my API router, here is the code to call the function:
user.controller.js
function register(req, res) {
var user = {
uname : req.body.uname,
email : req.body.email,
password : req.body.password
}
userService.create(user)
.then(function(){
res.status(200).json({ success: true, message: 'User Created!' });
})
.catch(function(err){
res.status(400).send(err);
})
}
It's working properly when I run the function and the data stored on mongoDB. The one that I want to know is, I've added unique
property on both uname and email, so when I am trying to create duplicated value on either one, it will generate an error. This is the body error that has been 'catched'
{
"code":11000,
"index":0,
"errmsg":"E11000 duplicate key error collection: flash-card.users index: name_1 dup key: { : null }",
"op":{/*Contain all info that want to be registered*/}
}
I tried to create duplicated value but it was showing the same error above without indicate which property that have duplicate value. Any other idea/approach to get specified on which property that got error/duplicate value?
Upvotes: 0
Views: 784
Reputation: 203519
The clues are there:
collection: flash-card.users
index: name_1
dup key: { : null }
It looks like your schema once has a property called name
(inferred from the index name) that was marked unique.
I think that at some point, you renamed that property (possibly to uname
), but the unique index on name
does not get automatically removed when you do that.
Instead, for every new document, MongoDB will assume that your document has a name
property with value null
(this behaviour is documented here, starting with "By contrast, ..."), and once the first document has been inserted, any subsequent document will trigger the E11000 error.
To solve this problem, you need to remove the name_1
index (which you have to do from the Mongo shell, or something like RoboMongo/Robo 3T perhaps).
Upvotes: 2