Implementation of nodejs using Sequelize framework to operate database

  • 2021-08-31 07:19:28
  • OfStack

sequelize.define

Using this method, you can define model, as shown below:


const Sequelize = require('sequelize');

var sequelize = new Sequelize(config.database, config.username, config.password, {
 host: config.host,
 dialect: 'mysql',
 pool: {
  max: 5,
  min: 0,
  idle: 30000
 }
});

var Website = sequelize.define('website', {
 id: {
  type: Sequelize.BIGINT,
  primaryKey: true,
  autoIncrement: true
 },
 url: Sequelize.STRING(255),
 title: Sequelize.STRING(255),
 status: Sequelize.INTEGER,
 delete_mark: Sequelize.BOOLEAN
}, {
 timestamps: false
});

The first parameter passed in by this method is the singular form of the data table. How do you understand it? For example, website is passed in here, which is actually the model name, and the data table defaults to the plural form of websites, which I also encountered in Laravel.

That is to say, the contract is greater than the definition, that is to say, if we all develop according to the agreed specifications, the efficiency is actually much higher than redefining.

So, when the model is defined, how should we use it?


(async () => {
 let demo = await Website.create({
  url:'http://www.xxxx.com/',
  title:'demo'
 });
 console.log(demo);
})();

Inheriting Model


const {Sequelize, DataTypes, Model} = require('sequelize');
const config = require('../config');

const sequelize = new Sequelize(config.database, config.username, config.password, {
 host: config.host,
 dialect: 'mysql',
 pool: {
  max: 5,
  min: 0,
  idle: 30000
 }
});

/**
 * @author chaojilaji
 *  Data table websites Relational object mapping based on 
 */
class WebSite extends Model {

}

WebSite.init({
 id: {
  type: Sequelize.BIGINT,
  primaryKey: true,
  autoIncrement: true
 },
 url: Sequelize.STRING(255),
 title: Sequelize.STRING(255),
 status: Sequelize.INTEGER,
 delete_mark: Sequelize.BOOLEAN
}, {
 sequelize,
 modelName: 'Website',
 timestamps:false
});

(async () => {
 await sequelize.sync();
 let x = await WebSite.create({
  url: 'http://www.xxxxxxxx.com/',
  title: 'demo2'
 });
 console.log(x);
})();

module.exports = WebSite;

I recommend inheriting Model, by creating an class, so that the model can be encapsulated using model. exports = module name. For other places to use, just need require to go in.

How to operate the data table is relatively simple, just refer to API. sequelize Document Address


Related articles: