不要怂,就是干,撸起袖子干!

Commit 197ba548 by Pedro Augusto de Paula Barbosa Committed by Sushant

docs: improve getting-started documentation (#10548)

1 parent 03a2b3f0
Showing with 160 additions and 120 deletions
# Sequelize
[![npm version](https://img.shields.io/npm/v/sequelize.svg)](https://www.npmjs.com/package/sequelize)
[![Build Status](https://travis-ci.org/sequelize/sequelize.svg?branch=master)](https://travis-ci.org/sequelize/sequelize)
[![Windows Build status](https://ci.appveyor.com/api/projects/status/9l1ypgwsp5ij46m3/branch/master?svg=true)](https://ci.appveyor.com/project/sushantdhiman/sequelize/branch/master)
[![codecov](https://codecov.io/gh/sequelize/sequelize/branch/master/graph/badge.svg)](https://codecov.io/gh/sequelize/sequelize)
[![npm version](https://badgen.net/npm/v/sequelize)](https://www.npmjs.com/package/sequelize)
[![Travis Build Status](https://badgen.net/travis/sequelize/sequelize?icon=travis)](https://travis-ci.org/sequelize/sequelize)
[![Appveyor Build Status](https://ci.appveyor.com/api/projects/status/9l1ypgwsp5ij46m3/branch/master?svg=true)](https://ci.appveyor.com/project/sushantdhiman/sequelize/branch/master)
[![npm downloads](https://badgen.net/npm/dm/sequelize)](https://www.npmjs.com/package/sequelize)
[![codecov](https://badgen.net/codecov/c/github/sequelize/sequelize?icon=codecov)](https://codecov.io/gh/sequelize/sequelize)
[![Last commit](https://badgen.net/github/last-commit/sequelize/sequelize)](https://github.com/sequelize/sequelize)
[![Merged PRs](https://badgen.net/github/merged-prs/sequelize/sequelize)](https://github.com/sequelize/sequelize)
[![GitHub stars](https://badgen.net/github/stars/sequelize/sequelize)](https://github.com/sequelize/sequelize)
[![Bountysource](https://www.bountysource.com/badge/team?team_id=955&style=bounties_received)](https://www.bountysource.com/teams/sequelize/issues?utm_source=Sequelize&utm_medium=shield&utm_campaign=bounties_received)
[![Slack Status](http://sequelize-slack.herokuapp.com/badge.svg)](http://sequelize-slack.herokuapp.com/)
[![npm downloads](https://img.shields.io/npm/dm/sequelize.svg?maxAge=2592000)](https://www.npmjs.com/package/sequelize)
![node](https://img.shields.io/node/v/sequelize.svg)
[![License](https://img.shields.io/npm/l/sequelize.svg?maxAge=2592000?style=plastic)](https://github.com/sequelize/sequelize/blob/master/LICENSE)
[![node](https://badgen.net/npm/node/sequelize)](https://www.npmjs.com/package/sequelize)
[![License](https://badgen.net/github/license/sequelize/sequelize)](https://github.com/sequelize/sequelize/blob/master/LICENSE)
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, read replication and more.
Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.
Sequelize follows [SEMVER](http://semver.org). Supports Node v6 and above to use ES6 features.
## v5 Release
You can find upgrade guide and changelog [here](https://github.com/sequelize/sequelize/blob/master/docs/upgrade-to-v5.md)
```bash
npm install --save sequelize # will install v5
```
You can find the upgrade guide and changelog in [upgrade-to-v5.md](https://github.com/sequelize/sequelize/blob/master/docs/upgrade-to-v5.md).
## Table of Contents
- [Installation](#installation)
......@@ -30,18 +31,16 @@ npm install --save sequelize # will install v5
## Installation
```bash
$ npm install --save sequelize
$ npm install --save sequelize # This will install v5
# And one of the following:
$ npm install --save pg pg-hstore
$ npm install --save pg pg-hstore # Postgres
$ npm install --save mysql2
$ npm install --save mariadb
$ npm install --save sqlite3
$ npm install --save tedious # MSSQL
$ npm install --save tedious # Microsoft SQL Server
```
Sequelize follows [SEMVER](http://semver.org). Supports Node v6 and above to use ES6 features.
## Documentation
- [v5 Documentation](http://docs.sequelizejs.com)
- [v4 Documentation](https://github.com/sequelize/sequelize/blob/v4/docs)
......@@ -49,12 +48,13 @@ Sequelize follows [SEMVER](http://semver.org). Supports Node v6 and above to use
- [Contributing](https://github.com/sequelize/sequelize/blob/master/CONTRIBUTING.md)
## Responsible disclosure
If you have any security issue to report, contact project maintainers privately. You can find contact information [here](https://github.com/sequelize/sequelize/blob/master/CONTACT.md)
If you have any security issue to report, contact project maintainers privately. You can find contact information in [CONTACT.md](https://github.com/sequelize/sequelize/blob/master/CONTACT.md).
## Resources
- [Changelog](https://github.com/sequelize/sequelize/releases)
- [Slack](http://sequelize-slack.herokuapp.com/)
- [Stack Overflow](https://stackoverflow.com/questions/tagged/sequelize.js)
### Tools
- [Sequelize & TypeScript](https://github.com/RobinBuschmann/sequelize-typescript)
......@@ -68,4 +68,4 @@ If you have any security issue to report, contact project maintainers privately.
### Translations
- [English v5](http://docs.sequelizejs.com) (OFFICIAL)
- [中文文档 v4](https://github.com/demopark/sequelize-docs-Zh-CN) (UNOFFICIAL)
\ No newline at end of file
- [中文文档 v4](https://github.com/demopark/sequelize-docs-Zh-CN) (UNOFFICIAL)
# Getting started
## Installation
In this tutorial you will learn to make a simple setup of Sequelize to learn the basics.
Sequelize is available via NPM and Yarn.
## Installing
```bash
// Using NPM
$ npm install --save sequelize
Sequelize is available via [npm](https://www.npmjs.com/package/sequelize) (or [yarn](https://yarnpkg.com/package/sequelize)).
# And one of the following:
$ npm install --save pg pg-hstore
```sh
npm install --save sequelize
```
You also have to install manually the driver for the database of your choice:
```sh
# 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 // MSSQL
// Using Yarn
$ yarn add sequelize
# And one of the following:
$ yarn add pg pg-hstore
$ yarn add mysql2
$ yarn add mariadb
$ yarn add sqlite3
$ yarn add tedious // MSSQL
$ npm install --save tedious # Microsoft SQL Server
```
## 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.
To connect to the database, you must create a Sequelize instance. This can be done by passing the connection parameters separately to the Sequelize constructor or by passing a single connection URI directly:
```js
const Sequelize = require('sequelize');
// Option 1: Passing parameters separately
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql'|'mariadb'|'sqlite'|'postgres'|'mssql',
dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
});
// Option 2: Using a connection URI
const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');
```
The Sequelize constructor takes a whole slew of options that are documented in the [API Reference for the Sequelize constructor](/class/lib/sequelize.js~Sequelize.html#instance-constructor-constructor).
### Note: setting up SQLite
If you're using SQLite, you should use the following instead:
```js
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: 'path/to/database.sqlite'
});
```
### Note: connection pool (production)
If you're connecting to the database from a single process, you should create only one Sequelize instance. Sequelize will setup a connection pool on initialization. This connection pool can be configured with the construction options (using `options.pool`). Example:
```js
const sequelize = new Sequelize(/* ... */, {
// ...
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:pass@example.com:5432/dbname');
```
The Sequelize constructor takes a whole slew of options that are available via the [API reference](/class/lib/sequelize.js~Sequelize.html).
Learn more in the [API Reference for the Sequelize constructor](/class/lib/sequelize.js~Sequelize.html#instance-constructor-constructor). If you're connecting to the database from multiple processes, you'll have to create one instance per process, but each instance should have a maximum connection pool size of such that the total maximum size is respected. For example, if you want a max connection pool size of 90 and you have three processes, the Sequelize instance of each process should have a max connection pool size of 30.
## Test the connection
### Testing the connection
You can use the `.authenticate()` function like this to test the connection.
You can use the `.authenticate()` function to test if the connection is OK:
```js
sequelize
......@@ -68,91 +84,114 @@ sequelize
});
```
## Your first model
### Closing the connection
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).
Models are defined with `sequelize.define('name', {attributes}, {options})`.
## Modeling a table
Models are defined with `sequelize.define('name', attributes, options)`:
```js
const User = sequelize.define('user', {
firstName: {
type: Sequelize.STRING
type: Sequelize.STRING,
allowNull: false
},
lastName: {
type: Sequelize.STRING
// allowNull defaults to true
}
});
// force: true will drop the table if it already exists
User.sync({force: true}).then(() => {
// Table created
return User.create({
firstName: 'John',
lastName: 'Hancock'
});
});
```
You can read more about creating models at [Model API reference](/class/lib/model.js~Model.html)
## Your first query
```js
User.findAll().then(users => {
console.log(users)
})
```
The above code tells Sequelize to expect a table named `users` in the database with the fields `firstName` and `lastName`. The table name is automatically pluralized by default (a library called [inflection](https://www.npmjs.com/package/inflection) is used under the hood to do this). This behavior can be stopped for a specific model by using the `freezeTableName: true` option, or for all models by using the `define` option from the Sequelize constructor.
You can read more about finder functions on models like `.findAll()` at [Data retrieval](/manual/models-usage.html#data-retrieval-finders) or how to do specific queries like `WHERE` and `JSONB` at [Querying](/manual/querying.html).
Sequelize also defines by default the fields `id` (primary key), `createdAt` and `updatedAt` to every model. This behavior can also be changed, of course (check the API Reference to learn more about the available options).
### Application wide model options
### Changing the default model options
The Sequelize constructor takes a `define` option which will be used as the default options for all defined models.
The Sequelize constructor takes a `define` option which will change the default options for all defined models.
```js
const sequelize = new Sequelize('connectionUri', {
const sequelize = new Sequelize(connectionURI, {
define: {
timestamps: false // true by default
// The `timestamps` field specify whether or not the `createdAt` and `updatedAt` fields will be created.
// This was true by default, but now is false by default
timestamps: false
}
});
const User = sequelize.define('user', {}); // timestamps is false by default
const Post = sequelize.define('post', {}, {
timestamps: true // timestamps will now be true
// Here `timestamps` will be false, so the `createdAt` and `updatedAt` fields will not be created.
const Foo = sequelize.define('foo', { /* ... */ });
// Here `timestamps` is directly set to true, so the `createdAt` and `updatedAt` fields will be created.
const Bar = sequelize.define('bar', { /* ... */ }, { timestamps: true });
```
You can read more about creating models in the [define API Reference](/class/lib/sequelize.js~Sequelize.html#instance-method-define) and the [Model API reference](/class/lib/model.js~Model.html).
## Synchronizing the model with the database
If you want Sequelize to automatically create the table (or modify it as needed) according to your model definition, you can use the `sync` method, as follows:
```js
// Note: using `force: true` will drop the table if it already exists
User.sync({ force: true }).then(() => {
// Now the `users` table in the database corresponds to the model definition
return User.create({
firstName: 'John',
lastName: 'Hancock'
});
});
```
## Promises
### Synchronizing all models at once
Sequelize uses [Bluebird](http://bluebirdjs.com) promises to control async control-flow.
Instead of calling `sync()` for every model, you can call `sequelize.sync()` which will automatically sync all models.
**Note:** _Sequelize use independent copy of Bluebird instance. You can access it using
`Sequelize.Promise` if you want to set any Bluebird specific options_
### Note for production
If you are unfamiliar with how promises work, don't worry, you can read up on them [here](http://bluebirdjs.com/docs/why-promises.html).
In production, you might want to consider using Migrations instead of calling `sync()` in your code. Learn more in the [Migrations](http://docs.sequelizejs.com/manual/migrations.html) guide.
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
## Querying
A few simple queries are shown below:
```js
// DON'T DO THIS
user = User.findOne()
// Find all users
User.findAll().then(users => {
console.log("All users:", JSON.stringify(users, null, 4));
});
console.log(user.get('firstName'));
```
// Create a new user
User.create({ firstName: "Jane", lastName: "Doe" }).then(jane => {
console.log("Jane's auto-generated ID:", jane.id);
});
_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:
// Delete everyone named "Jane"
User.destroy({
where: {
firstName: "Jane"
}
}).then(() => {
console.log("Done");
});
```js
User.findOne().then(user => {
console.log(user.get('firstName'));
// Change everyone without a last name to "Doe"
User.update({ lastName: "Doe" }, {
where: {
lastName: null
}
}).then(() => {
console.log("Done");
});
```
When your environment or transpiler supports [async/await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) this will work but only in the body of an [async](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) function:
Sequelize has a lot of options for querying. You will learn more about those in the next tutorials. It is also possible to make raw SQL queries, if you really need them.
```js
user = await User.findOne()
## Promises and async/await
console.log(user.get('firstName'));
```
As shown above by the extensive usage of `.then` calls, Sequelize uses Promises extensively. This means that, if your Node version supports it, you can use ES2017 `async/await` syntax for all asynchronous calls made with Sequelize.
Once you've got the hang of what promises are and how they work, use the [bluebird API reference](http://bluebirdjs.com/docs/api-reference.html) as your go-to tool. In particular, you'll probably be using [`.all`](http://bluebirdjs.com/docs/api/promise.all.html) a lot.
Also, all Sequelize promises are in fact [Bluebird](http://bluebirdjs.com) promises, so you have the rich Bluebird API to use as well (for example, using `finally`, `tap`, `tapCatch`, `map`, `mapSeries`, etc). You can access the Bluebird constructor used internally by Sequelize with `Sequelize.Promise`, if you want to set any Bluebird specific options.
......@@ -5,31 +5,33 @@
<div class="center sequelize">Sequelize</span>
</div>
[![Travis build](https://img.shields.io/travis/sequelize/sequelize/master.svg?style=flat-square)](https://travis-ci.org/sequelize/sequelize)
[![npm](https://img.shields.io/npm/dm/sequelize.svg?style=flat-square)](https://npmjs.org/package/sequelize)
[![npm](https://img.shields.io/npm/v/sequelize.svg?style=flat-square)](https://github.com/sequelize/sequelize/releases)
[![npm version](https://badgen.net/npm/v/sequelize)](https://www.npmjs.com/package/sequelize)
[![Travis Build Status](https://badgen.net/travis/sequelize/sequelize?icon=travis)](https://travis-ci.org/sequelize/sequelize)
[![Appveyor Build Status](https://ci.appveyor.com/api/projects/status/9l1ypgwsp5ij46m3/branch/master?svg=true)](https://ci.appveyor.com/project/sushantdhiman/sequelize/branch/master)
[![npm downloads](https://badgen.net/npm/dm/sequelize)](https://www.npmjs.com/package/sequelize)
[![codecov](https://badgen.net/codecov/c/github/sequelize/sequelize?icon=codecov)](https://codecov.io/gh/sequelize/sequelize)
[![Last commit](https://badgen.net/github/last-commit/sequelize/sequelize)](https://github.com/sequelize/sequelize)
[![Merged PRs](https://badgen.net/github/merged-prs/sequelize/sequelize)](https://github.com/sequelize/sequelize)
[![GitHub stars](https://badgen.net/github/stars/sequelize/sequelize)](https://github.com/sequelize/sequelize)
[![Bountysource](https://www.bountysource.com/badge/team?team_id=955&style=bounties_received)](https://www.bountysource.com/teams/sequelize/issues?utm_source=Sequelize&utm_medium=shield&utm_campaign=bounties_received)
[![Slack Status](http://sequelize-slack.herokuapp.com/badge.svg)](http://sequelize-slack.herokuapp.com/)
[![node](https://badgen.net/npm/node/sequelize)](https://www.npmjs.com/package/sequelize)
[![License](https://badgen.net/github/license/sequelize/sequelize)](https://github.com/sequelize/sequelize/blob/master/LICENSE)
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
Sequelize is a promise-based ORM for Node.js v6 and up. It supports the dialects PostgreSQL, MariaDB, MySQL, SQLite and MSSQL and features solid transaction support, relations, read replication and more.
Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.
## Example usage
Sequelize follows [SEMVER](http://semver.org). Supports Node v6 and above to use ES6 features.
**Sequelize v5** was released on March 13, 2019.
You are currently looking at the **Tutorials and Guides** for Sequelize. You might also be interested in the [API Reference](identifiers).
## Quick example
```js
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql'|'mariadb'|'sqlite'|'postgres'|'mssql',
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
// SQLite only
storage: 'path/to/database.sqlite'
});
const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');
const User = sequelize.define('user', {
username: Sequelize.STRING,
......@@ -46,4 +48,4 @@ sequelize.sync()
});
```
Please use [Getting Started](manual/getting-started) to learn more. If you wish to learn about Sequelize API please use [API Reference](identifiers)
To learn more about how to use Sequelize, read the tutorials available in the left menu. [Begin with Getting Started](manual/getting-started).
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!