根据Mongoose模式validation对象而不保存为新文档

我试图validation一些将被插入到一个新文档中的数据,但不是在很多其他事情需要发生之前。 所以我打算给静态方法添加一个函数,希望能够在模型模式中validation数组中的对象。

下面是代码:

module.exports = Mongoose => { const Schema = Mongoose.Schema const peopleSchema = new Schema({ name: { type: Schema.Types.String, required: true, minlength: 3, maxlength: 25 }, age: Schema.Types.Number }) /** * Validate the settings of an array of people * * @param {array} people Array of people (objects) * @return {boolean} */ peopleSchema.statics.validatePeople = function( people ) { return _.every(people, p => { /** * How can I validate the object `p` against the peopleSchema */ }) } return Mongoose.model( 'People', peopleSchema ) } 

所以peopleSchema.statics.validatePeople是我试图做validation的地方。 我已经通过了mongooses validation文档的阅读,但是没有说明如何在不保存数据的情况下对模型进行validation。

这可能吗?

更新

这里的答案之一指出我正确的validation方法,似乎工作,但现在它抛出一个Unhandled rejection ValidationError

下面是用于validation数据的静态方法( 插入它)

 peopleSchema.statics.testValidate = function( person ) { return new Promise( ( res, rej ) => { const personObj = new this( person ) // FYI - Wrapping the personObj.validate() in a try/catch does NOT suppress the error personObj.validate( err => { if ( err ) return rej( err ) res( 'SUCCESS' ) } ) }) } 

然后继续testing它:

 People.testValidate( { /* Data */ } ) .then(data => { console.log('OK!', data) }) .catch( err => { console.error('FAILED:',err) }) .finally(() => Mongoose.connection.close()) 

用不符合模式规则的数据进行testing会抛出错误,正如你所看到的,我尝试去捕捉它,但似乎并不奏效。

PS我使用蓝鸟为我的承诺

有一种方法可以通过Custom validators 。 validation失败时,无法将文档保存到数据库中。

 var peopleSchema = new mongoose.Schema({ name: String, age: Number }); var People = mongoose.model('People', peopleSchema); peopleSchema.path('name').validate(function(n) { return !!n && n.length >= 3 && n.length < 25; }, 'Invalid Name'); function savePeople() { var p = new People({ name: 'you', age: 3 }); p.save(function(err){ if (err) { console.log(err); } else console.log('save people successfully.'); }); } 

或者通过validate()与您定义的相同模式来做到这一点。

 var p = new People({ name: 'you', age: 3 }); p.validate(function(err) { if (err) console.log(err); else console.log('pass validate'); });