【发布时间】:2019-02-27 09:44:15
【问题描述】:
我创建了一个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:无法设置未定义的属性“名称”
this 怎么可能是未定义的?
如果我修改传递对象的方法,我可以让它按我的意愿工作,但它看起来很脏而且不正确,因为我想做的就是通过它的方法更改对象的属性..
// modified method of Schema
UserSchema.methods.setName = (User, name) => {
User.name = name + '123'
}
// modified call from the controller
UserModel.setName(name)
【问题讨论】:
-
我认为这是一个上下文问题。尝试将实例绑定到函数。 UserSchema.methods.setName = function (name) { this.name = name + '123' }.bind(UserSchema)
标签: javascript node.js express mongoose