不要 运行 在特定条件下对架构进行验证

Don't run validation on schema under certain conditions

我有一个包含多个必填字段的架构。当我使用 published:false 道具保存文档时,我想 运行 任何验证并按原样保存文档。后来published:true的时候,我要运行全部验证。

我认为这行得通:

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

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

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

请试试这个,

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...