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?
Sequelize set up Install Sequelize database driver for the database you would like to use by running one of the commands below. Install npm package Sequelize-CLI. Create a project folder. In your project folder path, run the command below to initialize Sequelize in the folder.
Instances are the individual results from a Sequelize call. In SequelizeMock, these objects have most of the same attributes as in the normal Sequelize Instance, however they also have a few additional bits of functionality.
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) { }
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 () {..}
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