"this" 在下面的代码中指的是什么?
What does "this" refers to in the code below?
我在看一些教程,在那里我找到了一段代码stuck.Please帮助我理解这个code.I在我的评论中标记了问题。
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 中的一个 "pre-save" 中间件是 "document middleware".
...in document middleware, this
refers to the document being updated.
所以this
指的是要保存的文件
这也提供了关于 isModified
是什么的线索:它是一种文档方法,可用于检查特定字段(在本例中为 password
)自文档以来是否已被修改之前从数据库中检索到。
在您发布的代码中,如果密码未更改,则无需再次对其进行哈希处理(使用 bcrypt
),因此调用 next
可跳过该步骤并从中间件返回。
isModified
记录在此处:http://mongoosejs.com/docs/api.html#document_Document-isModified
我在看一些教程,在那里我找到了一段代码stuck.Please帮助我理解这个code.I在我的评论中标记了问题。
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 中的一个 "pre-save" 中间件是 "document middleware".
...in document middleware,
this
refers to the document being updated.
所以this
指的是要保存的文件
这也提供了关于 isModified
是什么的线索:它是一种文档方法,可用于检查特定字段(在本例中为 password
)自文档以来是否已被修改之前从数据库中检索到。
在您发布的代码中,如果密码未更改,则无需再次对其进行哈希处理(使用 bcrypt
),因此调用 next
可跳过该步骤并从中间件返回。
isModified
记录在此处:http://mongoosejs.com/docs/api.html#document_Document-isModified