饭叔的知识整理

sequelize--ORM for node

常见操作:

var Sequelize=require('sequelize');
//连接数据库
var sequelize = new Sequelize('mysql://spiderman:spiderman@localhost/testdb',{logging: false});//logging:false不显示sql语句
//创建对象
var QQVideo=sequelize.define('tysp_video_info', {
  vid: {field: 'ROW_ID',type: Sequelize.STRING, primaryKey: true,uniqueKey:true },
  title:{field: 'TITLE',type: Sequelize.STRING},
  num:{field: 'PLAY_NUM',type: Sequelize.INTEGER},
}, {
  freezeTableName: true, // Model tableName will be the same as the model name,
  charset: 'utf8',
  collate: 'utf8_unicode_ci',
  createdAt   : 'CREATETIME', //Sequelize会自动增加createdAt和updatedAt字段,
  updatedAt   : 'UPDATETIME', //这里给它们换个字段名
});

//sync({force:false})如果没有表会新建
//sync({force:true}) 不管有没有表都会删了原来的新建
QQVideo.sync({force:false}).then(function () {
      return QQVideo.upsert(info); //upsert是update或者insert,前提是得有唯一主键
    });

function save(info){
  return QQVideo.upsert(info);
}

function findEmptyOne(){
  return QQVideo.findOne({ where: {title: null} });
}

function countEmptyOne(){
  return QQVideo.count({ where: {title: null} });
}

function findEmptyAll(){
  return QQVideo.findAll({ where: {title: null} });
}

function find10(){
  return QQVideo.findAll({ where: {title: null},limit: 10  });
}


findEmptyOne().then(function  (qqvideo) { 
    var plainJSON=qqvideo.get({
        plain: true  
      });
      //注意使用get({plain:true})后得到才是和数据库对应的JSON对象
    console.log(plainJSON);
});

参考

http://docs.sequelizejs.com/en/latest/docs/getting-started/