gpt4 book ai didi

node.js - 根据 Mongoose 模式验证对象而不另存为新文档

转载 作者:可可西里 更新时间:2023-11-01 10:24:43 25 4
gpt4 key购买 nike

我正在尝试验证一些将被插入到新文档中的数据,但在许多其他事情需要发生之前。因此,我打算向静态方法中添加一个函数,该函数有望根据模型架构验证数组中的对象。

到目前为止的代码如下:

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 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 来实现我的 promise

最佳答案

有一种方法可以通过 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.');
});
}

或通过 validate() 实现的另一种方式与您定义的架构相同。

var p = new People({
name: 'you',
age: 3
});

p.validate(function(err) {
if (err)
console.log(err);
else
console.log('pass validate');
});

关于node.js - 根据 Mongoose 模式验证对象而不另存为新文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35109811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com