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

Commit 172272c8 by Mick Hansen

Merge pull request #5170 from sushantdhiman/fix-docs-2

Few more documents updates
2 parents e67a9b3f 21065c37
......@@ -21,7 +21,7 @@ TODO - a link to bluebird + general promise syntax + catch / error handling
Now that your computer is prepared and your coffee sits next to your keyboard,
we can finally get started. First things first: create a directory and initialize it with NPM!
```bash
```bash
$ mkdir my-project
$ cd my-project
$ npm init
......@@ -29,7 +29,7 @@ $ npm init
NPM will ask you a couple of questions. Answer them or just hit the return key until it's satisfied.
Once done, you can install Sequelize and the connector for your database of choice.
```bash
$ npm install --save sequelize
$ npm install --save pg # for postgres
......@@ -72,15 +72,15 @@ As this article is for beginners, we will skip migrations for now and take a clo
### Defining a model
In order to let Sequelize create schemas in the database, you need to describe what kind of data you want to store. This can be done with `sequelize.define`:
```js
var User = sequelize.define('User', {
var User = sequelize.define('user', {
username: Sequelize.STRING,
password: Sequelize.STRING
});
```
This will define a user model that has a username and password. Furthermore, Sequelize will automatically add the columns `id`, `createdAt` and `updatedAt`. `createdAt` and `updatedAt` are controlled by Sequelize - when you `create` a model through Sequelize, `createdAt` will be set, and whenever you call `updateAttributes` / `save` on a model, `updatedAt` will be set.
This will define a user model that has a username and password. Furthermore, Sequelize will automatically add the columns `id`, `createdAt` and `updatedAt`. `createdAt` and `updatedAt` are controlled by Sequelize - when you `create` a model through Sequelize, `createdAt` will be set, and whenever you call `updateAttributes` / `save` on a model, `updatedAt` will be set.
### Synchronizing the schema
......@@ -91,7 +91,7 @@ sequelize
.sync({ force: true })
.then(function(err) {
console.log('It worked!');
}, function (err) {
}, function (err) {
console.log('An error occurred while creating the table:', err);
});
```
......@@ -109,9 +109,9 @@ Please note, that `{ force: true }` will drop the `Users` table and re-create it
### Configuration
You might not need the timestamps or you might not want the plural of the model's name as table name, right? Luckily there are configuration possibilities for that:
```js
var User = sequelize.define('User', {
var User = sequelize.define('user', {
username: Sequelize.STRING,
password: Sequelize.STRING
}, {
......@@ -121,9 +121,9 @@ var User = sequelize.define('User', {
```
And just in case you want to customize the timestamp field names, you can do it like this:
```js
var User = sequelize.define('User', {
var User = sequelize.define('user', {
username: Sequelize.STRING,
password: Sequelize.STRING
}, {
......@@ -135,7 +135,7 @@ var User = sequelize.define('User', {
Furthermore you can introduce a `deletedAt` timestamp so models are not actually deleted when you call `destroy`. Adding a `deletedAt` timestamp is called making the model 'paranoid':
```js
var User = sequelize.define('User', {
var User = sequelize.define('user', {
username: Sequelize.STRING,
password: Sequelize.STRING
}, {
......@@ -146,8 +146,8 @@ var User = sequelize.define('User', {
## Creating and persisting instances
Sequelize allows the creation of instances in two ways. You can either `build` an object and `save` it afterwards. Or you can directly `create` an instance in the database:
```js
```js
var user = User.build({
username: 'john-doe',
password: generatePasswordHash('i-am-so-great')
......@@ -159,7 +159,7 @@ user.save().then(function() {
```
This persists the instance in a two step way. If you want to do everything at once, use the following approach:
```js
User.create({
username: 'john-doe',
......@@ -172,7 +172,7 @@ User.create({
## Reading data from the database
Every defined model has finder methods, with which you can read the database. Searching for a single item can be done with `Model.find`. Retrieval of multiple items needs the use of `Model.findAll`.
```js
User
.find({ where: { username: 'john-doe' } })
......@@ -199,10 +199,10 @@ Before taking a closer look at the code, it is critical to understand some detai
An association between one source and one target is called "one to one" or 1:1 association. It consists of a source that **has one** target and a target that **belongs to** a source.
Sequelize expects a foreign key in the target's schema. That means that there has to be an attribute respectively a column in the target's table.
```js
var Source = sequelize.define('Source', {})
, Target = sequelize.define('Target', {})
var Source = sequelize.define('source', {})
, Target = sequelize.define('target', {})
Source.hasOne(Target)
Target.belongsTo(Source)
......@@ -220,10 +220,10 @@ sequelize
An association between one source and many target is called "one to many" or 1:N association. It consists of a source that **has many** targets and some targets which **belong to** a source.
Sequelize expects a foreign key in the target's schema. That means that there has to be an attribute respectively a column in the target's table.
```js
var Source = sequelize.define('Source', {})
, Target = sequelize.define('Target', {})
var Source = sequelize.define('source', {})
, Target = sequelize.define('target', {})
Source.hasMany(Target)
Target.belongsTo(Source)
......@@ -241,10 +241,10 @@ sequelize
An association between many sources and many targets is called "many to many" or N:M association. It consists of sources which **have many** targets and some targets which **have many** sources.
Sequelize expects a junction table which contains a foreign key to the source table and a foreign key to the target table. A row in the table connects a source with a target.
```js
var Source = sequelize.define('Source', {})
, Target = sequelize.define('Target', {})
var Source = sequelize.define('source', {})
, Target = sequelize.define('target', {})
Source.hasMany(Target)
Target.hasMany(Source)
......@@ -260,10 +260,10 @@ sequelize
### Getting/Setting associations
Defining associations is nice, but won't give you any advantage if you cannot read or set associations. Of course Sequelize will add respective functions to your models. Depending on the type of association you will find different methods:
```js
var Source = sequelize.define('Source', {})
, Target = sequelize.define('Target', {});
var Source = sequelize.define('source', {})
, Target = sequelize.define('target', {});
Source.hasOne(Target);
Target.belongsTo(Source);
......@@ -295,7 +295,7 @@ sequelize.Promise.all([
### Clearing associations
Assuming we already defined the models (as in the previous code example) and synced the schema with the database, we can clear the associations like this:
```js
source.setTarget(null).then(function() {
return source.getTarget();
......@@ -307,10 +307,10 @@ source.setTarget(null).then(function() {
### Adding / removing associations
For 1:N and N:M associations it makes sense to not only set the associations, but also to add or remove associations. Furthermore checking for an association can be handy.
```js
var Source = sequelize.define('Source', {})
, Target = sequelize.define('Target', {});
var Source = sequelize.define('source', {})
, Target = sequelize.define('target', {});
Source.hasMany(Target);
Target.belongsTo(Source);
......@@ -356,11 +356,11 @@ return sequelize.Promise.all([
## A combined example
Now that you know the basics of Sequelize, you might want to see everything in a single program:
```js
var Sequelize = require('sequelize')
, sequelize = new Sequelize('database_name', 'username', 'password')
, User = sequelize.define('User', {
, User = sequelize.define('user', {
username: Sequelize.STRING,
password: Sequelize.STRING
});
......
......@@ -40,7 +40,7 @@ There are currently three ways to programmatically add hooks:
```js
// Method 1 via the .define() method
var User = sequelize.define('User', {
var User = sequelize.define('user', {
username: DataTypes.STRING,
mood: {
type: DataTypes.ENUM,
......@@ -83,7 +83,7 @@ User.afterValidate('myHookAfter', function(user, options, fn) {
Only a hook with name param can be removed.
```js
var Book = sequelize.define('Book', {
var Book = sequelize.define('book', {
title: DataTypes.STRING
})
......@@ -243,11 +243,11 @@ For the most part hooks will work the same for instances when being associated e
2. The only way to call beforeDestroy/afterDestroy hooks are on associations with `onDelete: 'cascade'` and the option `hooks: true`. For instance:
```js
var Projects = sequelize.define('Projects', {
var Projects = sequelize.define('projects', {
title: DataTypes.STRING
})
var Tasks = sequelize.define('Tasks', {
var Tasks = sequelize.define('tasks', {
title: DataTypes.STRING
})
......
......@@ -19,7 +19,7 @@ Built instances will automatically get default values when they were defined&col
```js
// first define the model
var Task = sequelize.define('Task', {
var Task = sequelize.define('task', {
title: Sequelize.STRING,
rating: { type: Sequelize.STRING, defaultValue: 3 }
})
......@@ -205,7 +205,7 @@ User.bulkCreate([
`bulkCreate` was originally made to be a mainstream/fast way of inserting records, however, sometimes you want the luxury of being able to insert multiple rows at once without sacrificing model validations even when you explicitly tell Sequelize which columns to sift through. You can do by adding a `validate: true` property to the options object.
```js
var Tasks = sequelize.define('Task', {
var Tasks = sequelize.define('task', {
name: {
type: Sequelize.STRING,
validate: {
......
......@@ -2,8 +2,8 @@ While out of the box Sequelize will seem a bit opinionated it's trivial to both
## Tables
```js
sequelize.define('User', {
sequelize.define('user', {
}, {
tableName: 'users'
});
......@@ -11,7 +11,7 @@ sequelize.define('User', {
## Fields
```js
sequelize.define('ModelName', {
sequelize.define('modelName', {
userId: {
type: Sequelize.INTEGER,
field: 'user_id'
......@@ -56,4 +56,4 @@ Task.belongsTo(Project, {foreignKey: 'tasks_pk'});
// N:M
User.hasMany(Role, {through: 'user_has_roles', foreignKey: 'user_role_user_id'});
Role.hasMany(User, {through: 'user_has_roles', foreignKey: 'roles_identifier'});
```
\ No newline at end of file
```
......@@ -4,12 +4,12 @@ To define mappings between a model and a table, use the `define` method. Sequeli
```js
var Project = sequelize.define('Project', {
var Project = sequelize.define('project', {
title: Sequelize.STRING,
description: Sequelize.TEXT
})
var Task = sequelize.define('Task', {
var Task = sequelize.define('task', {
title: Sequelize.STRING,
description: Sequelize.TEXT,
deadline: Sequelize.DATE
......@@ -19,7 +19,7 @@ var Task = sequelize.define('Task', {
You can also set some options on each column:
```js
var Foo = sequelize.define('Foo', {
var Foo = sequelize.define('foo', {
// instantiating will automatically set the flag to true if not set
flag: { type: Sequelize.BOOLEAN, allowNull: false, defaultValue: true},
......@@ -197,7 +197,7 @@ Getters and Setters can be defined in 2 ways (you can mix and match these 2 appr
### Defining as part of a property
```js
var Employee = sequelize.define('Employee', {
var Employee = sequelize.define('employee', {
name: {
type : Sequelize.STRING,
allowNull: false,
......@@ -231,7 +231,7 @@ Below is an example of defining the getters and setters in the model options. Th
Note that the `this.firstname` and `this.lastname` references in the `fullName` getter function will trigger a call to the respective getter functions. If you do not want that then use the `getDataValue()` method to access the raw value (see below).
```js
var Foo = sequelize.define('Foo', {
var Foo = sequelize.define('foo', {
firstname: Sequelize.STRING,
lastname: Sequelize.STRING
}, {
......@@ -281,7 +281,7 @@ Validations are automatically run on `create`, `update` and `save`. You can also
The validations are implemented by [validator.js][3].
```js
var ValidateMe = sequelize.define('Foo', {
var ValidateMe = sequelize.define('foo', {
foo: {
type: Sequelize.STRING,
validate: {
......@@ -372,7 +372,7 @@ Any error messages collected are put in the validation result object alongside t
An example:
```js
var Pub = Sequelize.define('Pub', {
var Pub = Sequelize.define('pub', {
name: { type: Sequelize.STRING },
address: { type: Sequelize.STRING },
latitude: {
......@@ -412,7 +412,7 @@ In this simple case an object fails validation if either latitude or longitude i
You can also influence the way Sequelize handles your column names:
```js
var Bar = sequelize.define('Bar', { /* bla */ }, {
var Bar = sequelize.define('bar', { /* bla */ }, {
// don't add the timestamp attributes (updatedAt, createdAt)
timestamps: false,
......@@ -438,7 +438,7 @@ var Bar = sequelize.define('Bar', { /* bla */ }, {
If you want sequelize to handle timestamps, but only want some of them, or want your timestamps to be called something else, you can override each column individually:
```js
var Foo = sequelize.define('Foo', { /* bla */ }, {
var Foo = sequelize.define('foo', { /* bla */ }, {
// don't forget to enable timestamps!
timestamps: true,
......@@ -457,7 +457,7 @@ var Foo = sequelize.define('Foo', { /* bla */ }, {
You can also change the database engine, e.g. to MyISAM. InnoDB is the default.
```js
var Person = sequelize.define('Person', { /* attributes */ }, {
var Person = sequelize.define('person', { /* attributes */ }, {
engine: 'MYISAM'
})
......@@ -470,7 +470,7 @@ var sequelize = new Sequelize(db, user, pw, {
Finally you can specify a comment for the table in MySQL and PG
```js
var Person = sequelize.define('Person', { /* attributes */ }, {
var Person = sequelize.define('person', { /* attributes */ }, {
comment: "I'm a table comment!"
})
```
......@@ -486,7 +486,7 @@ var Project = sequelize.import(__dirname + "/path/to/models/project")
// The model definition is done in /path/to/models/project.js
// As you might notice, the DataTypes are the very same as explained above
module.exports = function(sequelize, DataTypes) {
return sequelize.define("Project", {
return sequelize.define("project", {
name: DataTypes.STRING,
description: DataTypes.TEXT
})
......@@ -496,8 +496,8 @@ module.exports = function(sequelize, DataTypes) {
The `import` method can also accept a callback as an argument.
```js
sequelize.import('Project', function(sequelize, DataTypes) {
return sequelize.define("Project", {
sequelize.import('project', function(sequelize, DataTypes) {
return sequelize.define("project", {
name: DataTypes.STRING,
description: DataTypes.TEXT
})
......@@ -562,7 +562,7 @@ sequelize.sync({ force: true, match: /_test$/ });
Sequelize allows you to pass custom methods to a model and its instances. Just do the following:
```js
var Foo = sequelize.define('Foo', { /* attributes */}, {
var Foo = sequelize.define('foo', { /* attributes */}, {
classMethods: {
method1: function(){ return 'smth' }
},
......@@ -579,7 +579,7 @@ Foo.build().method2()
Of course you can also access the instance's data and generate virtual getters:
```js
var User = sequelize.define('User', { firstname: Sequelize.STRING, lastname: Sequelize.STRING }, {
var User = sequelize.define('user', { firstname: Sequelize.STRING, lastname: Sequelize.STRING }, {
instanceMethods: {
getFullname: function() {
return [this.firstname, this.lastname].join(' ')
......@@ -608,7 +608,7 @@ var sequelize = new Sequelize('database', 'username', 'password', {
})
// Example:
var Foo = sequelize.define('Foo', { /* attributes */});
var Foo = sequelize.define('foo', { /* attributes */});
Foo.method1()
Foo.method2()
Foo.build().method3()
......@@ -618,7 +618,7 @@ Foo.build().method3()
Sequelize supports adding indexes to the model definition which will be created during `Model.sync()` or `sequelize.sync`.
```js
sequelize.define('User', {}, {
sequelize.define('user', {}, {
indexes: [
// Create a unique index on email
{
......
......@@ -411,9 +411,9 @@ Project.sum('age', { where: { age: { $gt: 5 } } }).then(function(sum) {
When you are retrieving data from the database there is a fair chance that you also want to get associations with the same query - this is called eager loading. The basic idea behind that, is the use of the attribute `include` when you are calling `find` or `findAll`. Lets assume the following setup:
```js
var User = sequelize.define('User', { name: Sequelize.STRING })
, Task = sequelize.define('Task', { name: Sequelize.STRING })
, Tool = sequelize.define('Tool', { name: Sequelize.STRING })
var User = sequelize.define('user', { name: Sequelize.STRING })
, Task = sequelize.define('task', { name: Sequelize.STRING })
, Tool = sequelize.define('tool', { name: Sequelize.STRING })
Task.belongsTo(User)
User.hasMany(Task)
......@@ -436,8 +436,8 @@ Task.findAll({ include: [ User ] }).then(function(tasks) {
"id": 1,
"createdAt": "2013-03-20T20:31:40.000Z",
"updatedAt": "2013-03-20T20:31:40.000Z",
"UserId": 1,
"User": {
"userId": 1,
"user": {
"name": "John Doe",
"id": 1,
"createdAt": "2013-03-20T20:31:45.000Z",
......@@ -462,12 +462,12 @@ User.findAll({ include: [ Task ] }).then(function(users) {
"id": 1,
"createdAt": "2013-03-20T20:31:45.000Z",
"updatedAt": "2013-03-20T20:31:45.000Z",
"Tasks": [{
"tasks": [{
"name": "A Task",
"id": 1,
"createdAt": "2013-03-20T20:31:40.000Z",
"updatedAt": "2013-03-20T20:31:40.000Z",
"UserId": 1
"userId": 1
}]
}]
*/
......@@ -494,7 +494,7 @@ User.findAll({ include: [{ model: Tool, as: 'Instruments' }] }).then(function(us
"id": 1,
"createdAt": null,
"updatedAt": null,
"UserId": 1
"userId": 1
}]
}]
*/
......@@ -524,7 +524,7 @@ User.findAll({
"id": 1,
"createdAt": null,
"updatedAt": null,
"UserId": 1
"userId": 1
}]
}],
......@@ -538,7 +538,7 @@ User.findAll({
"id": 1,
"createdAt": null,
"updatedAt": null,
"UserId": 1
"userId": 1
}]
}],
*/
......@@ -606,7 +606,7 @@ User.findAll({
"id": 1,
"createdAt": null,
"updatedAt": null,
"UserId": 1,
"userId": 1,
"Teacher": { // 1:1 association
"name": "Jimi Hendrix"
}
......
......@@ -15,7 +15,7 @@ more.
var Sequelize = require('sequelize');
var sequelize = new Sequelize('database', 'username', 'password');
var User = sequelize.define('User', {
var User = sequelize.define('user', {
username: Sequelize.STRING,
birthday: Sequelize.DATE
});
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!