Skip to content

Instantly share code, notes, and snippets.

@bushidocodes
Last active November 21, 2016 04:30
Show Gist options
  • Save bushidocodes/269e048e34fe363ec2a95d50044de5c7 to your computer and use it in GitHub Desktop.
Save bushidocodes/269e048e34fe363ec2a95d50044de5c7 to your computer and use it in GitHub Desktop.
Sequelize Example
var Sequelize = require('sequelize');
var connection = new Sequelize('dbname', 'userid', 'pw', {
  host: 'localhost',
  dialect: 'sqlite'
});

var Pokemon = connection.define('pokemon', {
  name : {
    type: Sequelize.STRING,
    unique: true,
    allowNull: false,
    validate: {
      caseCheck : function(nameValue) { // Using Custom Validator
        var first = nameValue.charAt(0);
        if (first != first.toUppercase()) throw New Error('Pokemon names must be capitalized');
      },
      len : { // Using Built-in Validators
        args : [3, 20],
        msg: "Pokemon names should be between three and twenty characters"
      }
    }
  },
  description : {
    type: Sequelize.TEXT,
    unique: true,
    allowNull: false;
  },
  abilities : {
    type: Sequelize.TEXT,
    unique: false,
    allowNull: true
  }
});

connection.sync({
  force: true,
  logging: console.log
})
.then(function(){
  Pokemon.create({
    name: "Pikachu",
    description : "A cute lightning mouse",
    abilities : "Thunder, tackle, growl"
  })
  Pokemon.create({
    name: "Magikarp",
    description : "A stupid fish",
    abilities : null
  })
})
.catch(function(err){
  console.log(err);
});

Pokemon.create is the equivalent of Pokemon.build().then(save).

var req = {
  body : [
    {
      name: "Pikachu",
      description: "A cute ligtning mouse",
      abilities : "Thunder, tackle, growl",
      cute: true
    },
    {
      name: "Mewtwo",
      description : "An evil psychic",
      abilities : "Psychic"
    },
    {
      name: "Meowth",
      description : "A talking cat",
      abilities : "Payday, Scratch",
      cute: true
    },
    {
      name: "Charizard",
      description : "A feiry dragon",
      abilities : "Flamethrower, Wing attack"
    }
  ]
};

Pokemon.bulkCreate(req.body)
.then(()=>{
  Pokemon.findAll({
    attributes ; ['name'],
    where: {cute: true},
    order:  '"name" DESC'
  })
})
.then((pokemon) => {
  pokemon.forEach((aPokemon)=>{console.log(aPokemon.name + 'is cute!!!!');})
})
.catch(function(err){
  console.log(err);
});
var Trainer = connection.define('trainers', {
  name: {
    type
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment