我试图验证一些将插入到新文档中的数据,但在许多其他事情发生之前。所以我打算添加一个函数到静态方法,希望可以根据模型架构验证数组中的对象。
目前为止的代码:
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
是我试图进行验证的地方。我已经阅读了mongoose的验证文档,但它没有说明如何在不保存数据的情况下对模型进行验证。这是可能的吗?
更新
这里的一个答案指向了我正确的验证方法,似乎可以正常工作,但现在它抛出了一个Unhandled rejection ValidationError
。这是用于验证数据(无需插入)的静态方法。
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' )
} )
})
}
接下来是我测试它的过程:
People.testValidate( { /* Data */ } )
.then(data => {
console.log('OK!', data)
})
.catch( err => {
console.error('FAILED:',err)
})
.finally(() => Mongoose.connection.close())
测试不符合模式规则的数据会抛出错误,正如您所见,我试图捕获它,但似乎没有起作用。
P.S. 我正在使用Bluebird作为我的承诺库。