javascript - Express.js Mongoose : TypeError Cannot set property of undefined

标签 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)

我导入了对象并从我创建的 Controller 中调用了方法:

import User from './User'

exports.signup = (request, response) => {
  const name = 'Ignas'

  const UserModel = new User
  UserModel.setName(name)

  ...
}

由于某种原因,它向我抛出一个错误:

TypeError: Cannot set property "name" of undefined

this怎么可能是未定义的?

如果我修改传递对象的方法,我可以让它按我想要的方式工作,但它看起来又脏又不正确,因为我想做的就是通过它的方法更改对象的属性..

// modified method of Schema
UserSchema.methods.setName = (User, name) => {
  User.name = name + '123'
}

// modified call from the controller
UserModel.setName(name)

最佳答案

箭头函数不绑定(bind)自己的this 。他们使用词汇 this 。箭头函数按词法绑定(bind)其上下文,因此 this实际上指的是原始上下文。这称为词法作用域。词法作用域的含义是什么:

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.

您可以在 MDN 中找到有关此问题的更多说明。例如。

最后,它会寻找 this在所有父级上下文中,直到找到它为止,在您的情况下,因为在模块中没有 this 的定义任何地方,返回undefined

关于javascript - Express.js Mongoose : TypeError Cannot set property of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54902367/

相关文章:

javascript - 为什么我不能使用 _.map(new Array(n), Math.random) 创建一个随机数组?

javascript - jQuery 切换子类

javascript - 正则表达式负向前瞻以排除字符串

javascript - 加密单词循环将值从单词的末尾转移到每个字母java脚本

node.js - child_process 未在 docker 容器内收到 SIGTERM

javascript - 在node.js应用程序中, mdkirSync ('mydir' ,700) 导致权限 d-w------T

express - Express/Jade 中的相对链接

javascript - 插入 couchdb 数据库后未找到/丢失文档

node.js - Axios - 如何修复 - POST URL net::ERR_CONNECTION_RESET

javascript - 'NextHandleFunction' 类型的参数不可分配给 'PathParams' 类型的参数