[英]What does “this” refers to in the code below?
我在看一些教程時,發現有一段代碼被卡住了,請幫助我理解該代碼。我已經在注釋中標記了問題。
Code
UserSchema.pre('save', function(next){ //this is a pre hook which is used.understood.
var user = this; // what is the function of this?
var SALT_FACTOR = 5;
if(!user.isModified('password')){ //not understood.From where this function arises?I did not found this anywhere in mongoose tutorial/api.
return next();
}
bcrypt.genSalt(SALT_FACTOR, function(err, salt){
if(err){
return next(err);
}
Mongoose中的“預保存”中間件是“文檔中間件” 。
該文檔指出:
......在文檔中間件,
this
指的是文件被更新。
因此, this
是指要保存的文檔。
這也提供了有關isModified
是什么的線索:這是一個文檔方法,可用於檢查自從較早從數據庫檢索文檔以來,是否修改了特定字段(在這種情況下為password
。
在您發布的代碼中,如果未更改密碼,則無需再次對其進行哈希處理(使用bcrypt
),因此可以通過調用next
並從中間件返回來跳過該步驟。
isModified
記錄在這里: http : //mongoosejs.com/docs/api.html#document_Document-isModified
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.