【问题标题】:Don't run validation on schema under certain conditions不要在某些条件下对模式运行验证
【发布时间】:2016-03-18 12:37:31
【问题描述】:

我有一个包含多个必填字段的架构。当我使用 published:false 属性保存文档时,我希望 运行任何验证并按原样保存文档。后来published:true时,我要运行所有的验证。

我认为这会起作用:

MySchema.pre('validate', function(next) {
    if(this._doc.published === false) {
        //don't run validation
        next();
    }
    else {
        this.validate(next);
    }
});

但这不起作用,它会返回所需属性的验证错误。

那么如何在某些情况下不运行验证而在其他情况下运行呢?最优雅的方法是什么?

【问题讨论】:

    标签: node.js mongoose mongoose-schema


    【解决方案1】:

    请试试这个,

    TagSchema.pre('validate', function(next) {
        if (!this.published)
            next();
        else {
            var error = new mongoose.Error.ValidationError(this);
            next(error);
        }
    });
    

    测试架构

    var TagSchema = new mongoose.Schema({
        name: {type: String, require: true},
        published: Boolean,
        tags: [String]
    });
    

    publishedtrue

    var t = new Tag({
        published: true,
        tags: ['t1']
    });
    
    t.save(function(err) {
        if (err)
            console.log(err);
        else
            console.log('save tag successfully...');
    });
    

    结果:

    { [ValidationError: Tag validation failed]
      message: 'Tag validation failed',
      name: 'ValidationError',
      errors: {} }
    

    publishedfalse,结果是

    save tag successfully...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-03
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      • 2015-10-31
      • 1970-01-01
      • 2022-12-17
      相关资源
      最近更新 更多