【问题标题】:Sequelize v4 | Instance Methods not working续集 v4 |实例方法不起作用
【发布时间】:2020-05-16 01:44:25
【问题描述】:

我一直在尝试更新我的代码以适应 Sequelize 的最新升级。我正在使用

  • 续集:4.2.0

  • 节点:7.10.0

  • NPM:5.0.3

问题

我似乎无法正确设置用户模型。我已经实现了一些似乎不起作用的实例方法。类不能被正确实例化。

user.js

module.exports = (sequelize, DataTypes) => {
  var User = sequelize.define('user', {
    attributes ....
  }, { 
    hooks: { 
      afterCreate(user, options) {
        user.testFunction();
      }
    }
  });

  // Instance methods
  User.prototype.testFunction = () => {
    this.firstName = "John";
  }

  // Class methods
  User.anotherTestFunction = () => {
    User.findOne().then(() => doSomething());
  }

  return User;
}

index.js

var sequelize;
sequelize = new Sequelize(config.DATABASE_URL);

db.User = sequelize.import(__dirname + '/user.js');

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

usersController.js

var db = require('../path/to/db');

function create_post_function = (req, res) => {
  var body = getBody();
  db.User.create(body).then(user => respondSuccess());
}

现在,除了实例方法之外,此示例中的所有内容都可以正常运行!!!

我不断收到TypeError: Cannot set property 'firstName' of undefined

由于某种原因,它没有将实例方法应用于 sequelize 模型。很奇怪,但我可能做错了什么并且没有看到它。

非常感谢任何帮助!

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    您不能使用箭头函数,因为它们无法在适当的上下文中访问this(它将引用父作用域)。试着这样写 -

    // Instance methods
    User.prototype.testFunction = function testFunction() {
      this.firstName = "John";
    }
    
    // Class methods
    User.anotherTestFunction = function anotherTestFunction() {
      User.findOne().then(() => doSomething());
    }
    

    【讨论】:

    • 你刚刚拯救了我的一天。谢谢!
    • 找到答案我从未感到如此幸运。我不知道您不能将this 与箭头功能一起使用。我会浪费很多时间寻找错误的方向。
    • 其实你可以在箭头函数中使用'this',但是上下文将从父环境中设置。
    猜你喜欢
    • 2018-01-18
    • 2020-01-21
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多