猫鼬:改变w.r.t值的验证

时间:2015-09-22 11:48:15

标签: node.js mongodb validation

我有一个示例架构:

/** @var ServiceManager|\PHPUnit_Framework_MockObject_MockObject $smMock */
$smMock = $this->getMockBuilder('Zend\ServiceManager\ServiceManager')
    ->getMock();
$smMock->expects($this->at(0))
    ->method('get')
    ->with('Zend\Db\Adapter\Adapter')
    ->will($this->returnValue($adapterMock));
$smMock->expects($this->at(1))
    ->method('get')
    ->with('Intranet\Service\Model\PTypeaffaireService')
    ->will($this->returnValue($typeaffaireService));
$smMock->expects($this->at(2))
    ->method('get')
    ->with('Intranet\Service\Model\PEtataffaireService')
    ->will($this->returnValue($etataffaireService));
$smMock->expects($this->at(3))
    ->method('get')
    ->with('Maintenance\Service\Model\PMaiPrestationService')
    ->will($this->returnValue($maiPrestationService));

{ title: {type: String, required: true}, status: {type: String, enum: ['draft', 'status1', 'status2']}, value1: {type: String, required: true}, value2: {type: String, required: true} } 以外,我还在required: truevalue1上进行了一些其他验证,例如value2

RegExp

如果schema.path('title', function (value) { ... }); schema.path('value1', function (value) { ... }); schema.path('value2', function (value) { ... }); ,我想运行不同的验证。 对于例如只有status == drafttitle,其他验证将被忽略。

目前我这样做:

required

但这迫使我使用schema.method('saveDraft', function(next) { if (this.status == 'draft') { schema.set('validateBeforeSave', false); if (!this.title || this.title.length == 0) return next(Error("`title` is required")); } this.save(next); });

是否可以使用mydocument.saveDraft(cb)

2 个答案:

答案 0 :(得分:0)

你可以:

  • 覆盖架构的保存方法,它将验证然后调用标准保存方法(您将保存在代码中的某处)
  • 使用pre save hook(假设您使用的是猫鼬)

    schema.pre('save', function(next){
        ...
        next();
    });
    

答案 1 :(得分:0)

我想出了一种根据当前值运行不同验证的方法。

我应用了一个预验证器钩子:

bash -c 'echo $(date +%Y%m%d%H%M%S -r {}) > {}'
相关问题