2015-11-04 64 views
0

有沒有辦法檢查路徑是否在驗證程序中被修改?我需要檢查還是僅在路徑改變時才運行驗證程序?在驗證程序中獲得isModified

編輯:

更具體地說,我想,以確保一個作家存在之前,我插入一個ID:

var BookSchema = new Schema({ 
    title: { type: String, required: true }, 
    authorId: { type: Schema.Types.ObjectId, ref: 'Author' } 
    }); 

BookSchema.path('authorId').validate(function(authorId, done) { 
    Author.getAuthorById(authorId, function(err, author) { 
    if (err || !author) { 
     done(false); 
    } else { 
     done(true); 
    } 
    }); 
}, 'Invalid author, does not exist'); 

在這種情況下,我只希望如果AUTHORID設置此驗證或者如果它改變。我是否需要檢查在函數中是否發生了變化,或者我可以假設,如果authorId更改並且不爲null/undefined,那麼只會調用此驗證程序?

這使得它看起來像我可能會調用isModified,但我沒有看到這是'this'上的一個函數。 Mongoose validation only when changed

回答

1

是的,驗證器只在路徑改變時運行,並且它們也只在它們不是undefined時運行。除了必需的驗證程序,它在兩種情況下運行。