【发布时间】:2016-05-08 16:20:44
【问题描述】:
我正在尝试验证一些将被插入到新文档中的数据,但不是在许多其他事情需要发生之前。所以我打算在静态方法中添加一个函数,希望能根据模型模式验证数组中的对象。
这是目前为止的代码:
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 是我尝试进行验证的地方。我已通读 mongooses validation 文档,但没有说明如何在不保存数据的情况下验证模型。
这可能吗?
更新
这里的一个答案向我指出了正确的验证方法,这似乎有效,但现在它抛出了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 来兑现我的承诺
【问题讨论】:
-
@Justin 这对你有什么帮助?我正在尝试相同的方法并得到与您在评论中提到的相同的 UnhandledPromiseRejectionWarning 错误。
标签: node.js mongodb validation mongoose-schema