2011-09-10 55 views
5

我試圖做一些經典的事情來確保用戶的用戶名與Nodejs/Mongoose中的密碼不同。驗證多個Mongoose模式屬性?

我在想使用單獨的驗證函數會很好,但我不知道如何去做。

到目前爲止,我已經使用了model code from Alex Young's Notepad tutorial。他創建了我重新使用的虛擬password屬性。

我已經得到了基本的驗證如下:

function validatePresenceOf(value) { 
    return value && value.length; 
} 

User = new Schema({ 
    'username': { 
     type: String, 
     validate: [ 
      validatePresenceOf, 'a username is required', 
     ], 
     index: { unique: true } 
    }, 
}); 

我怎麼會允許一個驗證器來訪問其他屬性?

回答

8

您可以通過this.propertyToBeCalled調用模式的其他屬性。

schema.path('name').validate(function(v) { 
    if (v === this.password) { 
     return false; 
    } else { 
     return true; 
    } 
}, 'my error type'); 

或者類似的東西無論如何。