Подтвердить что ты не робот

Как поймать ошибку при вставке документа MongoDB, который нарушает уникальный индекс?

Я создаю приложение 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!' }

Примечание. После того, как я отправлю пользователя, я автоматически аутентифицирую, не нужен пароль или что-то еще.

4b9b3361

Ответ 1

Вам нужно будет проверить ошибку, возвращенную методом save, чтобы увидеть, была ли она выбрана для дублирующего имени пользователя.

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
    });

  });
})

Ответ 2

Вы также можете попробовать этот приятный пакет mongoose-unique-validator, который упрощает обработку ошибок, поскольку вы будете получите ошибку проверки Mongoose при попытке нарушить уникальное ограничение, а не ошибку E11000 от MongoDB:

var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');

// Define your schema as normal.
var userSchema = mongoose.Schema({
    username: { type: String, required: true, unique: true }
});

// You can pass through a custom error message as part of the optional options argument:
userSchema.plugin(uniqueValidator, { message: '{PATH} already exists!' });

Ответ 3

Попробуйте следующее:

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

        user.save(function(err) {
            if (err) {
                // you could avoid http status if you want. I put error 500 
                return res.status(500).send({
                    success: false,
                    message: 'User already exist!'
                });
            }

            res.json({
                success: true
            });

        });
    })