Skip to content

Instantly share code, notes, and snippets.

@AloofBuddha
Created September 26, 2016 14:28
Show Gist options
  • Save AloofBuddha/766d67f06c55c9f489ebf4c80356fe4a to your computer and use it in GitHub Desktop.
Save AloofBuddha/766d67f06c55c9f489ebf4c80356fe4a to your computer and use it in GitHub Desktop.
Sequelize cheat sheet

Note: $> means command line input

Dependencies

Dependencies to use Sequelize $> npm install --save sequelize pg pg-hstore

Setup

Must create the DB first $> createdb my-music

var Sequelize = require('sequelize');
var db = new Sequelize('postgres://localhost:5432/my-music');

Model

// Useful:  http://docs.sequelizejs.com/en/latest/docs/models-definition/#data-types
//          http://docs.sequelizejs.com/en/latest/docs/models-definition/#validations

// sequelize.define(modelName, modelDefinitionObject, configObject)
var Artist = db.define('artist', {     
  firstName: {
    type: Sequelize.STRING,
    allowNull: false
    
  },
  lastName: {
    type: Sequelize.STRING,
    validate: {
      notNull: true
    }
  },
  bandName: {
    type: Sequelize.STRING
    validate: {
      notIn: ["Creed", "DC Talk"]
    }
  }
}, {
  // this is an additional argument to define where your classMethods and hooks would go 
});

Express integration

You will generally want to ensure all Schemas are synced to the database before starting the server

app.js

var db = require('./db');
var Artist = db.Artist;

var allSynced = Promise.all([
  db.Artist.sync(),
  db.Album.sync(),
  db.Song.sync({ force: true })
]);

...

allSynced.then(() => {
  console.log('db synced');
  app.listen(3000, () => {
    console.log('server is running')
  });
});

.sync can take an options argument. { force: true } will wipe all values from the table before syncing (can be useful when developing)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment