2016-11-19 24 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; 
    } 
}