Installation

Sequelize is available via NPM.

  1. $ npm install --save sequelize
  2. # And one of the following:
  3. $ npm install --save pg pg-hstore
  4. $ npm install --save mysql // For both mysql and mariadb dialects
  5. $ npm install --save sqlite3
  6. $ npm install --save tedious // MSSQL

Setting up a connection

Sequelize will setup a connection pool on initialization so you should ideally only ever create one instance per database.

  1. var sequelize = new Sequelize('database', 'username', 'password', {
  2. host: 'localhost',
  3. dialect: 'mysql'|'mariadb'|'sqlite'|'postgres'|'mssql',
  4. pool: {
  5. max: 5,
  6. min: 0,
  7. idle: 10000
  8. },
  9. // SQLite only
  10. storage: 'path/to/database.sqlite'
  11. });
  12. // Or you can simply use a connection uri
  13. var sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');

The Sequelize constructor takes a whole slew of options that are available via the API reference.

Your first model

Models are defined with sequelize.define('name', {attributes}, {options}).

  1. var User = sequelize.define('user', {
  2. firstName: {
  3. type: Sequelize.STRING,
  4. field: 'first_name' // Will result in an attribute that is firstName when user facing but first_name in the database
  5. },
  6. lastName: {
  7. type: Sequelize.STRING
  8. }
  9. }, {
  10. freezeTableName: true // Model tableName will be the same as the model name
  11. });
  12. User.sync({force: true}).then(function () {
  13. // Table created
  14. return User.create({
  15. firstName: 'John',
  16. lastName: 'Hancock'
  17. });
  18. });

Many more options can be found in the Model API reference

Application wide model options

The Sequelize constructor takes a define option which will be used as the default options for all defined models.

  1. var sequelize = new Sequelize('connectionUri', {
  2. define: {
  3. timestamps: false // true by default
  4. }
  5. });
  6. var User = sequelize.define('user', {}); // timestamps is false by default
  7. var Post = sequelize.define('post', {}, {
  8. timestamps: true // timestamps will now be true
  9. });

Promises

Sequelize uses promises to control async control-flow. If you are unfamiliar with how promises work, now might be a good time to brush up on them, here and here

Basically a promise represents a value which will be present at some point - "I promise you I will give you a result or an error at some point". This means that

  1. // DON'T DO THIS
  2. user = User.findOne()
  3. console.log(user.get('firstName'));

will never work! This is because user is a promise object, not a data row from the DB. The right way to do it is:

  1. User.findOne().then(function (user) {
  2. console.log(user.get('firstName'));
  3. });

Once you've got the hang of what promises are and how they work, use the bluebird API reference as your go to tool. In particular, you'll probably be using .all a lot.