Jus*_*tin 5 validation mongodb node.js mongoose-schema
我正在尝试验证将要插入到新文档中的某些数据,但是在需要执行许多其他操作之前,这并不是必须的。因此,我将向静态方法添加一个函数,该函数有望针对模型模式验证数组中的对象。
到目前为止的代码如下:
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 )
}
Run Code Online (Sandbox Code Playgroud)
因此,这peopleSchema.statics.validatePeople就是我尝试进行验证的地方。我已经阅读了猫鼬验证文档,但没有说明如何在不保存数据的情况下针对模型进行验证。
这可能吗?
此处的答案之一将我引向了正确的验证方法,该方法似乎可行,但是现在抛出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' )
} )
})
}
Run Code Online (Sandbox Code Playgroud)
然后我在这里测试一下:
People.testValidate( { /* Data */ } )
.then(data => {
console.log('OK!', data)
})
.catch( err => {
console.error('FAILED:',err)
})
.finally(() => Mongoose.connection.close())
Run Code Online (Sandbox Code Playgroud)
使用不遵循架构规则的数据对其进行测试将抛出该错误,并且您可以看到,我尝试捕获该错误,但是它似乎不起作用。
PS Im使用Bluebird兑现承诺
有一种方法可以通过Custom validators. 当验证失败时,无法将文档保存到数据库中。
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.');
});
}
Run Code Online (Sandbox Code Playgroud)
或者使用您定义的相同架构来实现此目的的另一种方法validate()。
var p = new People({
name: 'you',
age: 3
});
p.validate(function(err) {
if (err)
console.log(err);
else
console.log('pass validate');
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7286 次 |
| 最近记录: |