How can I add a custom function to secelize.js file in Node.JS?
3 answers
Version 4 of sequelize changed this, and other solutions with instanceMethods
and classMethods
no longer work. See Upgrade to V4 / Breaking Changes
A new way to do it like this:
const Model = sequelize.define('Model', {
...
});
// Class Method
Model.myCustomQuery = function (param, param2) { };
// Instance Method
Model.prototype.myCustomSetter = function (param, param2) { }
+14
source to share
Use instanceMethods
like Jan Meyer .
In your client example:
// 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;
}
}
});
};
+4
source to share
I had the same problem, it worked for me to add a method to an object classMethods
// 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;
}
}
});
};
-1
source to share