[英]Express.js mongoose: TypeError Cannot set property of undefined
I created an UserSchema
and added a method in which i try to set it's property name
: 我创建了一个
UserSchema
并添加了一个尝试设置其属性name
:
import mongoose, { Schema } from 'mongoose'
const UserSchema = new Schema({
name: String
})
UserSchema.methods.setName = (name) => {
this.name = name + '123'
}
exports default mongoose.model('User', UserSchema)
I imported the object and called the method from the controller I created: 我导入了对象,并从我创建的控制器中调用了该方法:
import User from './User'
exports.signup = (request, response) => {
const name = 'Ignas'
const UserModel = new User
UserModel.setName(name)
...
}
For some reason it throws me an error: 由于某种原因,它引发了一个错误:
TypeError: Cannot set property "name" of undefined
TypeError:无法设置未定义的属性“名称”
How could this
be undefined? 怎么能
this
是不确定的?
If I modify a method passing the object I could make it working as I want, but it looks dirty and incorrect since all I want to do is to change object´s property through it´s method.. 如果我修改了一个传递对象的方法,则可以使它按我的意愿工作,但是它看起来很脏而且不正确,因为我要做的就是通过对象的方法来更改对象的属性。
// modified method of Schema
UserSchema.methods.setName = (User, name) => {
User.name = name + '123'
}
// modified call from the controller
UserModel.setName(name)
Arrow functions don't bind its own this
. 箭头函数不绑定它自己的
this
。 They use lexical this
. 他们使用词汇
this
。 Arrow functions lexically bind their context so this
actually refers to the originating context. 箭头功能词汇结合其上下文所以
this
实际上指的是起始上下文。 This is called lexical scoping. 这称为词汇作用域。 And what lexical scoping means:
词汇作用域的含义是:
Lexical scoping (sometimes known as static scoping ) is a convention used with many programming languages that sets the scope (range of functionality) of a variable so that it may only be called (referenced) from within the block of code in which it is defined.
词法作用域(有时称为静态作用域)是一种与许多编程语言一起使用的约定,用于设置变量的范围(功能范围),以便只能在定义该变量的代码块内调用(引用)该变量。
You have more explanations about this issue in MDN for example. 例如,您在MDN中有关于此问题的更多说明。
At the end, what it happens is that it will look for this
in all parent's context until it finds it, and in your case, because in the module there is not a definition of this
anywhere, returns undefined
. 最后,什么情况是,它会寻找
this
在所有父母的情况下,直到它找到它,你的情况,因为在模块中没有的定义this
在任何地方,返回undefined
。
You are using Arrow function
syntax, this
keyword with arrow function has some things mess. 您正在使用
Arrow function
语法, this
带有arrow函数的关键字有些混乱。
Hotfix: Use old school function syntax 修补程序:使用旧的学校函数语法
UserSchema.methods.setName = function(name) {
this.name = name + '123'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.