Il validatore mangusta è un ottimo posto per iniziare su un livello di modello, ma se è necessario disporre di convalida controller specifico, io uso il seguente codice in un file utils.js:
var async = require('async')
exports.validator = function (reqProps, props, mongoEnt, next) {
var propsErr = [];
var mongoErr = {};
async.parallel([function (cb) {
reqProps.forEach(function (rp) {
if (!props[rp])propsErr.push(rp);
})
cb()
}, function (cb) {
if (mongoEnt != null) {
var test = new mongoEnt(props);
test.validate(function (err) {
mongoErr = err;
cb();
});
} else {
mongoErr = null;
cb();
}
}], function (err, result) {
if (propsErr.length != 0) {
return next(new Error('The following props were not included: ' + propsErr));
} else if(mongoErr != null) {
return next(new Error('The following prop was not included: ' +mongoErr.errors[Object.keys(mongoErr.errors).pop()].path));
} else {
return next(null);
}
})
}
Questo mi permette per entrambi convalidare usando il validatore di mangusta e controllare gli oggetti aggiuntivi che includo nella proprietà reqProps in una riga di codice. Anche se questo è solo il controllo delle proprietà richieste, è possibile estenderlo facilmente per il proprio schema di convalida.
Un esempio di utilizzo di questo codice:
var Person = mongoose.model('Person')
exports.addUSCitizen = function(props, next){
utils.validator(['ssn'], props, Person, function (err) {
if(err) return next(err);
//do something using props.ssn
})
}