I
I
Ivan Soshnikov2017-03-17 13:36:37
Mongoose
Ivan Soshnikov, 2017-03-17 13:36:37

Nodejs + express + mongoose - how to implement custom form validation?

I decided to look at the node. All sorts of rakes of misunderstanding have so far managed to be solved, but here it stalled.
Form validation is performed by means of express-form. When adding a new entry, it is necessary to check the existence in the database (mongodb/mongoose) of an entry with the same name. To do this, use a custom validator:

form.validate("name").custom(programExistsValidator)

Validator:
const programExistsValidator = function (programName) {
    ImageProgram.findOne({name: programName}, function (err, data) {
        throw new Error("Программа с таким именем уже существует");
    });
};

Mongoose is asynchronous. The validator works and does not throw any exceptions and ends before the data is received from the mongo.
And actually the necessary logic of the validator works out after, in its own context.
How to implement such a check?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Soshnikov, 2017-03-17
@soshnikov

So, got it.
Ambush in the package description:
Which leads us to outdated documentation. The dandean/express-form project is currently closed. However, it was forked and supported by freewil/express-form. There is also more up-to-date documentation, in which there is such an example:

// Asynchronous custom validator (3 argument function signature)

    form.field('username').custom(function(value, source, callback) {
      username.check(value, function(err) {
        if (err) return callback(new Error('Invalid %s'));
        callback(null);
      });
    });

In my case it looks like this:
const programExistsValidator = function (programName, source, callback) {
    ImageProgram.findOne({name: programName}, function(err, data){
        if(err){
            return callback(new Error('Ошибка проверки названия. Ошибка БД.'))
        }
        if(data !== null){
            return callback(new Error('Программа с таким именем уже существует.'));
        }
        callback(null);
    });
};

Well, you can also note that it will suddenly come in handy for someone. `custom` is used for both validation and filtering. If we throw an exception, if we return a value - filtering.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question