Heads up! To view this whole video, sign in with your Courses Plus account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
In this video we'll introduce instance methods to our models.
Sequelize 4.0 and Instance Methods
In the video, the following code is used to define the publishedAt()
and shortDescription()
instance methods on the Article
model:
'use strict';
var dateFormat = require('dateformat');
module.exports = function(sequelize, DataTypes) {
var Article = sequelize.define('Article', {
title: DataTypes.STRING,
author: DataTypes.STRING,
body: DataTypes.TEXT
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
}
},
instanceMethods: {
publishedAt: function() {
return dateFormat(this.createdAt, "dddd, mmmm dS, yyyy, h:MM TT");
},
shortDescription: function(){
return this.body.length > 30 ? this.body.substr(0, 30) + "..." : this.body;
}
}
});
return Article;
};
Starting with Sequelize 4.0, class and instance methods are no longer defined via the sequelize.define()
method. Instead, you add them to the ES2015 class that's returned by the sequelize.define()
method call:
'use strict';
var dateFormat = require('dateformat');
module.exports = (sequelize, DataTypes) => {
const Article = sequelize.define('Article', {
title: DataTypes.STRING,
author: DataTypes.STRING,
body: DataTypes.TEXT
}, {});
Article.associate = function(models) {
// associations can be defined here
};
Article.prototype.publishedAt = function() {
return dateFormat(this.createdAt, "dddd, mmmm dS, yyyy, h:MM TT");
};
Article.prototype.shortDescription = function() {
return this.body.length > 30 ? this.body.substr(0, 30) + "..." : this.body;
};
return Article;
};
For more information about this change, see http://docs.sequelizejs.com/manual/tutorial/models-definition.html#expansion-of-models.
Sequelize Documentation
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up