How can I add a custom function to secelize.js file in Node.JS?

For example, I have a client model. I want to add a new function "sendEmail"

The function should work for sending email to one client or for sending email to multiple clients at once?

Where to define these functions?

+3


source to share


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


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


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







All Articles