2016-11-19 43 views
0

我想從我的預保存鉤子中調用一個函數,該鉤子更新正在保存/更新的實例中的屬性。我不想在schema方法中再次調用save()。另外,下面只是一個例子,但我有一些shema方法變得很長,我不想將它們包含在pre save鉤子中。從預保存鉤子和更新屬性中調用模式方法

UserSchema.pre('save', function(next) { 
    const user = this; 
    ... 
    if (user.isModified('something')) { 
    user.checkSomething(); 
    } 
    ... 
    next(); 
}); 

UserSchema.method.checkSomething() = function() { 
    const user = this; 

    if(user.something > 5) { 
    // Any way to update the below property without calling save() again? 
    user.somethingElse = true; 
    } 
} 

看來這個改變並不是永久性的,一旦函數返回。

謝謝。

回答

0

除了示例代碼中的拼寫錯誤,我唯一的猜測是checkSomething函數具有異步操作,並且pre-save中間件正在同步運行。

// include `done` for async operation 
UserSchema.pre('save', function(next, done) { 
    const user = this; 

    next(); 

    if (user.isModified('something')) { 
    // Assuming this is asynchronous 
    user.checkSomething(done); 
    } else { 
    done(); 
    } 
}); 

UserSchema.method('checkSomething', checkSomething); 

// Async function 
function checkSomething(cb) { 
    const user = this; 

    if (user.something > 5) { 
    doSomethingAsync(function(err, res) { 
     if (err) { 
     return cb(err); 
     } 

     user.somethingElse = res; 
     cb(); 
    }); 
    } else { 
    cb(); 
    } 
} 

注:如果要修改實例的值,我會建議在pre-validate步這樣做使模型可以在保存之前驗證修改後的值。

UserSchema.pre('validate', function(next) { 
    const user = this; 

    if (user.isModified('something')) { 
    // Assuming this is synchronous 
    user.checkSomething(); 
    } 

    next(); 
}); 

UserSchema.method('checkSomething', checkSomething); 

function checkSomething() { 
    const user = this; 

    if (user.something > 5) { 
    user.somethingElse = true; 
    } 
}