R
R
rusline2017-10-21 13:47:23
Node.js
rusline, 2017-10-21 13:47:23

How to correctly display a validation error for a unique value?

I'm a little new to node js. How to redefine the name of the error and in general do I display the validation correctly?
Here is what message
E11000 duplicate key error index displays: social_network.users.$username_1 dup key: { : "LOGIN" }
And at least it outputs that Such a user already exists, of course, there is an idea how to do this, in the message rendering and output this one there error, but I think that it is not reasonable to use
How I implemented in the model

let schema = new Schema({
    username: {
        type: String,
        index: {unique: true, message: 'Такой пользователь уже существует'},
        required: true
    },
    hashedPassword: {
        type: String,
        required: true
    },
    salt: {
        type: String,
        required: true
    },
    created: {
        type: Date,
        default: Date.now
    }
});
module.exports = mongoose.model('User', schema);

in view
router.get('/registration', (req, res, next) => {
    res.render('registration', {
        title: 'Регитрация',
    })
});

router.post('/registration', (req, res) => {
    let user = {
        username: req.body.username,
        password: req.body.password
    };
    let data = new User(user);
    data.save().then((doc) => {
        console.log('Сохранение объекта', doc);
        res.redirect('/')
    }).catch((err) => {
        console.error(err);
        res.render('registration', {
            title: 'Регистрация',
            message: err.message,
        });
    })
});

And in the template
extends layout

block content
    if(message)
        p=message
    .container
        h1=title
        form(method='post')
            div(class='input-field col s6')
                input#username(type='text', name='username' required=true, class='validate')
                label(for='username') Имя пользователя
            div(class='input-field col s6')
                input#password(type='password', name='password' required=true, class='validate')
                label(for='password') Пароль
            button(class='waves-effect waves-light btn') Зарегестрировать пользователя
        a(href='/') Войти в систему

I don't understand how to do it

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
levchak0910, 2017-10-22
@rusline

mongoose-beautiful-unique-validation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question