Javascript Express.js mongoose:TypeError无法设置未定义的属性
我创建了一个Javascript Express.js mongoose:TypeError无法设置未定义的属性,javascript,node.js,express,mongoose,Javascript,Node.js,Express,Mongoose,我创建了一个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
,并添加了一个方法,试图在其中设置它的属性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)
我导入了该对象并从我创建的控制器调用了该方法:
import User from './User'
exports.signup = (request, response) => {
const name = 'Ignas'
const UserModel = new User
UserModel.setName(name)
...
}
出于某种原因,它给我带来了一个错误:
TypeError:无法设置未定义的属性“name”
这个
怎么可能是未定义的
如果我修改了一个传递对象的方法,我可以让它按照我想要的方式工作,但它看起来脏而且不正确,因为我所要做的就是通过它的方法更改对象的属性
// modified method of Schema
UserSchema.methods.setName = (User, name) => {
User.name = name + '123'
}
// modified call from the controller
UserModel.setName(name)
箭头函数不绑定自己的
此。他们使用词法这个。箭头函数在词汇上绑定其上下文,因此此
实际上指的是原始上下文。这称为词汇范围界定。词汇范围界定的含义是:
词汇范围界定(有时称为静态范围界定)是一种惯例
与设置范围(范围)的许多编程语言一起使用
变量的功能),以便只能调用它
(引用)在定义它的代码块中
例如,您对这个问题有更多的解释
最后,它会在所有父对象的上下文中查找this
,直到找到它为止。在您的情况下,因为模块中没有this
的定义,所以返回undefined
您使用的是箭头函数
语法,这个带有箭头函数的关键字有些混乱
修补程序:使用老式函数语法
UserSchema.methods.setName = function(name) {
this.name = name + '123'
}
我认为这是一个背景问题。尝试将实例绑定到函数。UserSchema.methods.setName=函数(名称){this.name=name+'123'}.bind(UserSchema)