I've been trying to update my code to accommodate the newest upgrades to Sequelize. I'm using
我一直在尝试更新我的代码,以适应Sequelize的最新升级。我在用着
Sequelize: 4.2.0
Node: 7.10.0
NPM: 5.0.3
The Problem
I can't seem to set the User model properly. I've implemented some instance methods that don't seem to be working. The class must not be instantiated properly.
我似乎无法正确设置用户模型。我已经实现了一些似乎不起作用的实例方法。该类不能正确实例化。
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());
}
Now, everything in this example works perfectly EXCEPT the instance method!!!
现在,此示例中的所有内容都完美地工作,除了实例方法!
I'm continually getting TypeError: Cannot set property 'firstName' of undefined
我不断得到TypeError:无法设置未定义的属性'firstName'
For some reason, it's not applying the instance method to the sequelize Model. Very strange, but I'm probably doing something noticeably wrong and not seeing it.
由于某种原因,它没有将实例方法应用于续集模型。很奇怪,但我可能做了一些明显错误的事情并没有看到它。
Really appreciate any help!
真的很感激任何帮助!
1 个解决方案
#1
20
You can't use arrow functions since they can't access this
. Try writing them like this -
您无法使用箭头功能,因为他们无法访问此功能。试着像这样写它们 -
// Instance methods
User.prototype.testFunction = function testFunction() {
this.firstName = "John";
}
// Class methods
User.anotherTestFunction = function anotherTestFunction() {
User.findOne().then(() => doSomething());
}
#1
20
You can't use arrow functions since they can't access this
. Try writing them like this -
您无法使用箭头功能,因为他们无法访问此功能。试着像这样写它们 -
// Instance methods
User.prototype.testFunction = function testFunction() {
this.firstName = "John";
}
// Class methods
User.anotherTestFunction = function anotherTestFunction() {
User.findOne().then(() => doSomething());
}