根据Mongoose模式验证对象,而无需另存为新文档 [英] Validate object against Mongoose schema without saving as a new document

查看:109
本文介绍了根据Mongoose模式验证对象,而无需另存为新文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证将要插入到新文档中的某些数据,但并不是在需要执行许多其他操作之前.因此,我打算向静态方法中添加一个函数,以期针对模型模式验证数组中的对象.

I'm trying to validate some data that will be inserted into a new document, but not before a lot of other things need to happen. So I was going to add a function to the static methods that would hopefully validate objects in an array against he model schema.

到目前为止,这里的代码:

Heres the code thus far:

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是我尝试进行验证的地方.我已经阅读过猫鼬验证文档,但没有说明如何在没有模型的情况下针对模型进行验证保存数据.

So the peopleSchema.statics.validatePeople is where I'm trying to do the validation. I have read through mongooses validation documents, but it doesn't state how to validate against a model without saving the data.

这可能吗?

这里的一个答案将我引向了正确的验证方法,该方法似乎可行,但是现在抛出了Unhandled rejection ValidationError.

One of the answers on here pointed me towards the proper validation method, which seems to work, but now its throwing an Unhandled rejection ValidationError.

此处使用用于验证数据的静态方法(不插入)

Heres the static method used to validate data (without inserting it)

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' )
        } )
    })
}

然后我在这里对其进行测试:

Then heres me testing it out:

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

使用不遵循架构规则的数据对其进行测试将抛出该错误,并且您可以看到,我尝试捕获它,但是它似乎没有用.

Testing it out with data that doesnt follow the schema rules will throw the error, and as you can see, I try to catch it, but it doesnt seem to work.

P.S..我使用Bluebird履行诺言

P.S. Im using Bluebird for my promises

推荐答案

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

There is one way to do that through Custom validators. When the validation failed, failed to save document into DB.

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() 进行此操作的另一种方法您定义的.

Or another way to do that through validate() with same schema as you defined.

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

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

这篇关于根据Mongoose模式验证对象,而无需另存为新文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆