I've been trying to update my code to accommodate the newest upgrades to Sequelize. I'm using
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
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!
There are two ways you can define instance methods with Sequelize: Adding the function to the prototype object. Adding the function to the model created using ES6 class.
findByPk() Finds a single active record with the specified primary key. CActiveRecord.
Function fnCreates a object representing a database function. This can be used in search queries, both in where and order parts, and as default values in column definitions. If you want to refer to columns in your function, you should use sequelize.
Sequelize supports the concept of paranoid tables. A paranoid table is one that, when told to delete a record, it will not truly delete it. Instead, a special column called deletedAt will have its value set to the timestamp of that deletion request.
You can't use arrow functions since they can't access this
in the appropriate context (it will reference the parent scope). 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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With