Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom function to sequelize.js in Node.JS?

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?

like image 888
Aminadav Glickshtein Avatar asked May 07 '15 12:05

Aminadav Glickshtein


People also ask

How do I make a node JS Sequelize model?

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.

What is Sequelize instance?

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.


Video Answer


3 Answers

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) {  }
like image 194
jlh Avatar answered Oct 19 '22 07:10

jlh


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;
      }
    }
  });
};
like image 21
Bernardo Bosak de Rezende Avatar answered Oct 19 '22 08:10

Bernardo Bosak de Rezende


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 () {..}
like image 1
taevas Avatar answered Oct 19 '22 09:10

taevas