簡體   English   中英

以下代碼中的“ this”指的是什么?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM