1. 程式人生 > >Sequelize-nodejs-1-getting started

Sequelize-nodejs-1-getting started

Sequelize is a promise-based ORM for Node.js v4 and up. It supports the dialects PostgreSQL, MySQL, SQLite and MSSQL and features solid transaction support, relations, read replication and more.

Sequelize是一種基於promise的ORM(物件關係對映),支援nodejs版本4及以上。它支援PostgreSQL、MySQL、SQLite和MSSQL語言,並具有可靠的事務支援、關係、讀複製等特性。

 

安裝:

// Using NPM
$ npm install --save sequelize
$ npm install --save mysql2

我使用的是mysql,所以安裝的是上面兩個模組

⚠️要安裝mysql2,否則報錯:

Error: Please install mysql2 package manually

 相應的其他對應安裝:

$ npm install --save pg pg-hstore
$ npm install --save mysql2
$ npm install --save sqlite3
$ 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 if you're connecting to the DB from a single process. If you're connecting to the DB from multiple processes, you'll have to create one instance per process, but each instance should have a maximum connection pool size of "max connection pool size divided by number of instances". So, if you wanted a max connection pool size of 90 and you had 3 worker processes, each process's instance should have a max connection pool size of 30.

Sequelize將在初始化時設定一個連線池,因此理想情況下,如果從單個程序連線到資料庫,那麼每個資料庫應該只建立一個例項。如果要從多個程序連線到資料庫,必須為每個程序建立一個例項,但是每個例項的最大連線池大小應該是“最大連線池大小除以例項數量”。因此,如果您希望最大連線池大小為90,並且您有3個工作程序,那麼每個程序的例項的最大連線池大小應該為30。

const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: 'mysql'|'sqlite'|'postgres'|'mssql',
  operatorsAliases: false,

  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  },

  // SQLite only
  storage: 'path/to/database.sqlite'
});

// Or you can simply use a connection uri
const sequelize = new Sequelize('postgres://user:[email protected]:5432/dbname');

 

Test the connection

You can use the .authenticate() function like this to test the connection.

sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });

 

Promises (如果不瞭解什麼是promise,可以看本部落格js同步-非同步-回撥 )

Sequelize uses Bluebird promises to control async control-flow.

Note: Sequelize use independent copy of Bluebird instance. You can access it using Sequelize.Promise if you want to set any Bluebird specific options

If you are unfamiliar with how promises work, don't worry, you can read up on them 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

// DON'T DO THIS
user = User.findOne()
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:

User.findOne().then(user => {
  console.log(user.get('firstName'));
});

When your environment or transpiler supports async/await this will work but only in the body of an asyncfunction:

user = await User.findOne()
console.log(user.get('firstName'));

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.