Я создаю приложение MEAN.
Это моя схема имени, имя пользователя должно быть уникальным.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports = mongoose.model('User', new Schema({
username: { type: String, unique: true }
}));
В моем почтовом маршруте я сохраняю пользователя следующим образом:
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
});
});
})
Если я снова отправлю сообщение с тем же именем пользователя, я получу эту ошибку:
MongoError: insertDocument:: вызвано:: 11000 E11000 дубликат ключа индекс ошибки:
Может кто-нибудь объяснить, как вместо ошибки отправить json как { succes: false, message: 'User already exist!' }
Примечание. После того, как я отправлю пользователя, я автоматически аутентифицирую, не нужен пароль или что-то еще.