Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
150
rated 0 times [  152] [ 2]  / answers: 1 / hits: 36045  / 9 Years ago, tue, june 2, 2015, 12:00:00

I'm building a MEAN app.



This is my Username schema, the username should be unique.



var mongoose = require('mongoose');
var Schema = mongoose.Schema;

module.exports = mongoose.model('User', new Schema({
username: { type: String, unique: true }
}));


On my post route I save the user like this:



app.post('/authenticate', function(req, res) {
var user = new User({
username: req.body.username
});

user.save(function(err) {
if (err) throw err;

res.json({
success: true
});

});
})


If I post with the same username again I get this error:




MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key
error index:




Can someone explain how instead of the error to send a json like { succes: false, message: 'User already exist!' }



Note: After I post the user I will automatically authentificate, dont need password or something else.


More From » mongodb

 Answers
200

You will need to test the error returned from the save method to see if it was thrown for a duplicative username.



app.post('/authenticate', function(req, res) {
var user = new User({
username: req.body.username
});

user.save(function(err) {
if (err) {
if (err.name === 'MongoError' && err.code === 11000) {
// Duplicate username
return res.status(422).send({ succes: false, message: 'User already exist!' });
}

// Some other error
return res.status(422).send(err);
}

res.json({
success: true
});

});
})

[#66374] Saturday, May 30, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kamryn

Total Points: 645
Total Questions: 100
Total Answers: 118

Location: Tanzania
Member since Wed, Feb 24, 2021
3 Years ago
;