sequelizejs中文文档(一)入门
入门
安装
Sequelize 支持 NPM 和 Yarn 的安装。
// Using NPM $ npm install --save sequelize # And one of the following: $ npm install --save pg pg-hstore $ npm install --save mysql2 $ npm install --save sqlite3 $ npm install --save tedious // MSSQL // Using Yarn $ yarn add sequelize # And one of the following: $ yarn add pg pg-hstore $ yarn add mysql2 $ yarn add sqlite3 $ yarn add tedious // MSSQL
建立连接
Sequelize将在初始化时设置连接池,如果从单个进程连接到数据库,则最好能在每个数据库中创建一个实例。 如果要从多个进程连接到数据库,则必须为每个进程创建一个实例,但每个实例应具有“最大连接池大小除以实例数”的最大连接池大小。 因此,如果您希望最大连接池大小为90,并且有3个工作进程,则每个进程的实例应具有30的最大连接池大小。
const sequelize = new Sequelize('database', 'username', 'password', { host: 'localhost', dialect: 'mysql'|'sqlite'|'postgres'|'mssql', pool: { max: 5, min: 0, idle: 10000 }, // SQLite only storage: 'path/to/database.sqlite' }); // Or you can simply use a connection uri const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');
测试连接
您可以使用.authenticate()函数来测试连接。
sequelize .authenticate() .then(() => { console.log('Connection has been established successfully.'); }) .catch(err => { console.error('Unable to connect to the database:', err); });
你第一个 model
Models 的定义格式 sequelize.define('name', {attributes}, {options})。
const User = sequelize.define('user', { firstName: { type: Sequelize.STRING }, lastName: { type: Sequelize.STRING } }); // force: true will drop the table if it already exists User.sync({force: true}).then(() => { // Table created return User.create({ firstName: 'John', lastName: 'Hancock' }); });
你第一个查询
User.findAll().then(users => {
console.log(users)
})
应用model options
const sequelize = new Sequelize('connectionUri', { define: { timestamps: false // true by default } }); const User = sequelize.define('user', {}); // timestamps is false by default const Post = sequelize.define('post', {}, { timestamps: true // timestamps will now be true });
Promises
Sequelize使用Promises来控制异步控制流程。如果你不熟悉Promises,去百度吧。
// DON'T DO THIS user = User.findOne() console.log(user.get('firstName'));
这将不会得到正确的值,因为user是一个Promises对象,正确的做法是:
User.findOne().then(user => { console.log(user.get('firstName')); });