入门
在本教程中,你将学习如何对 Sequelize 进行简单的设置。
¥In this tutorial, you will learn to make a simple setup of Sequelize.
安装
¥Installing
¥Sequelize is available via npm (or yarn).
npm install --save sequelize
你还必须为你选择的数据库手动安装驱动程序:
¥You'll also have to manually install the driver for your database of choice:
# One of the following:
$ npm install --save pg pg-hstore # Postgres
$ npm install --save mysql2
$ npm install --save mariadb
$ npm install --save sqlite3
$ npm install --save tedious # Microsoft SQL Server
$ npm install --save oracledb # Oracle Database
连接到数据库
¥Connecting to a database
要连接到数据库,你必须创建一个 Sequelize 实例。这可以通过将连接参数单独传递给 Sequelize 构造函数或传递单个连接 URI 来完成:
¥To connect to the database, you must create a Sequelize instance. This can be done by either passing the connection parameters separately to the Sequelize constructor or by passing a single connection URI:
const { Sequelize } = require('sequelize');
// Option 1: Passing a connection URI
const sequelize = new Sequelize('sqlite::memory:') // Example for sqlite
const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname') // Example for postgres
// Option 2: Passing parameters separately (sqlite)
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: 'path/to/database.sqlite'
});
// Option 3: Passing parameters separately (other dialects)
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: /* one of 'mysql' | 'postgres' | 'sqlite' | 'mariadb' | 'mssql' | 'db2' | 'snowflake' | 'oracle' */
});
Sequelize 构造函数接受很多选项。它们记录在 API 参考。
¥The Sequelize constructor accepts a lot of options. They are documented in the API Reference.
测试连接
¥Testing the connection
你可以使用 .authenticate()
函数测试连接是否正常:
¥You can use the .authenticate()
function to test if the connection is OK:
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
关闭连接
¥Closing the connection
Sequelize 默认情况下会保持连接打开,并为所有查询使用相同的连接。如果需要关闭连接,调用 sequelize.close()
(异步,返回 Promise)。
¥Sequelize will keep the connection open by default, and use the same connection for all queries. If you need to close the connection, call sequelize.close()
(which is asynchronous and returns a Promise).
一旦调用了 sequelize.close()
,就不可能打开新连接。你将需要创建一个新的 Sequelize 实例才能再次访问你的数据库。
¥Once sequelize.close()
has been called, it's impossible to open a new connection. You will need to create a new Sequelize instance to access your database again.
术语约定
¥Terminology convention
请注意,在上面的示例中,Sequelize
指的是库本身,而 sequelize
指的是 Sequelize 的一个实例,它表示与一个数据库的连接。这是推荐的约定,整个文档都将遵循该约定。
¥Observe that, in the examples above, Sequelize
refers to the library itself while sequelize
refers to an instance of Sequelize, which represents a connection to one database. This is the recommended convention and it will be followed throughout the documentation.
阅读文档的提示
¥Tip for reading the docs
我们鼓励你在阅读 Sequelize 文档时在本地运行代码示例。这将帮助你学得更快。最简单的方法是使用 SQLite 方言:
¥You are encouraged to run code examples locally while reading the Sequelize docs. This will help you learn faster. The easiest way to do this is using the SQLite dialect:
const { Sequelize, Op, Model, DataTypes } = require('sequelize');
const sequelize = new Sequelize('sqlite::memory:');
// Code here! It works!
要尝试其他方言(这些方言更难在本地设置),你可以使用 Sequelize SSCCE GitHub 存储库,它允许你直接从 GitHub 免费运行所有受支持的方言的代码,无需任何设置!
¥To experiment with the other dialects, which are harder to set up locally, you can use the Sequelize SSCCE GitHub repository, which allows you to run code on all supported dialects directly from GitHub, for free, without any setup!
新数据库与现有数据库
¥New databases versus existing databases
如果你从头开始一个项目,并且你的数据库仍然是空的,则可以从头开始使用 Sequelize 来自动创建数据库中的每个表。
¥If you are starting a project from scratch, and your database is still empty, Sequelize can be used from the beginning in order to automate the creation of every table in your database.
另外,如果你想使用 Sequelize 连接到已填充表和数据的数据库,也同样有效!Sequelize 可以帮助你解决这两种情况。
¥Also, if you want to use Sequelize to connect to a database that is already filled with tables and data, that works as well! Sequelize has got you covered in both cases.
日志
¥Logging
默认情况下,Sequelize 将针对其执行的每个 SQL 查询登录到控制台。options.logging
选项可用于自定义此行为,方法是定义每次 Sequelize 记录某些内容时执行的函数。默认值为 console.log
,使用该值时,仅显示日志函数调用的第一个日志参数。例如,对于查询日志记录,第一个参数是原始查询,第二个参数(默认情况下隐藏)是 Sequelize 对象。
¥By default, Sequelize will log into the console for every SQL query it performs. The options.logging
option can be used to customize this behavior, by defining the function that gets executed every time Sequelize logs something. The default value is console.log
and when using that only the first log parameter of a log function call is displayed. For example, for query logging the first parameter is the raw query and the second (hidden by default) is the Sequelize object.
options.logging
的常用有用值:
¥Common useful values for options.logging
:
const sequelize = new Sequelize('sqlite::memory:', {
// Choose one of the logging options
logging: console.log, // Default, displays the first parameter of the log function call
logging: (...msg) => console.log(msg), // Displays all log function call parameters
logging: false, // Disables logging
logging: msg => logger.debug(msg), // Use custom logger (e.g. Winston or Bunyan), displays the first parameter
logging: logger.debug.bind(logger), // Alternative way to use custom logger, displays all messages
});
Promise 和 async/await
¥Promises and async/await
Sequelize 提供的大多数方法都是异步的,因此返回 Promises。它们都是 Promise,因此你可以开箱即用 Promise API(例如,使用 then
、catch
、finally
)。
¥Most of the methods provided by Sequelize are asynchronous and therefore return Promises. They are all Promises, so you can use the Promise API (for example, using then
, catch
, finally
) out of the box.
当然,使用 async
和 await
也可以。
¥Of course, using async
and await
works fine as well.