For example I have a Client model. I want to add new function "sendEmail"
The function needs to work send email to one client, or to send email to many clients at once?
Where to define those functions?
For example I have a Client model. I want to add new function "sendEmail"
The function needs to work send email to one client, or to send email to many clients at once?
Where to define those functions?
Version 4 of sequelize has changed this and the other solutions with instanceMethods and classMethods do not work anymore. See Upgrade to V4 / Breaking changes
The new way of doing it is as follows:
const Model = sequelize.define('Model', {
...
});
// Class Method
Model.myCustomQuery = function (param, param2) { };
// Instance Method
Model.prototype.myCustomSetter = function (param, param2) { }
myCustomSetter is undefined when accessed from outside the Model? I am having this problem. Any hint?Use instanceMethods as Jan Meier pointed out.
In your client sample:
// models/Client.js
'use strict';
module.exports = function(sequelize, DataTypes) {
return sequelize.define('Client', {
first_name: DataTypes.STRING,
last_name: DataTypes.STRING,
}, {
instanceMethods: {
getFullName: function() {
return this.first_name + ' ' + this.last_name;
}
}
});
};
https://sequelize.org/v4/manual/tutorial/upgrade-to-v4.html#config-options
Removed classMethods and instanceMethods options from sequelize.define. Sequelize models are now ES6 classes. You can set class / instance level methods like this
Old
const Model = sequelize.define('Model', {
...
}, {
classMethods: {
associate: function (model) {...}
},
instanceMethods: {
someMethod: function () { ...}
}
});
New
const Model = sequelize.define('Model', {
...
});
// Class Method
Model.associate = function (models) {
...associate the models
};
// Instance Method
Model.prototype.someMethod = function () {..}
I had the same problem, for me it worked to add the method in the classMethods object
// models/Client.js
'use strict';
module.exports = function(sequelize, DataTypes) {
return sequelize.define('Client', {
first_name: DataTypes.STRING,
last_name: DataTypes.STRING,
}, {
classMethods: {
getFullName: function() {
return this.first_name + ' ' + this.last_name;
}
}
});
};