@@ -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
varUser=sequelize.define('User',{
varUser=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
varUser=sequelize.define('User',{
varUser=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
varUser=sequelize.define('User',{
varUser=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
varUser=sequelize.define('User',{
varUser=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
varuser=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
varSource=sequelize.define('Source',{})
,Target=sequelize.define('Target',{})
varSource=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
varSource=sequelize.define('Source',{})
,Target=sequelize.define('Target',{})
varSource=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
varSource=sequelize.define('Source',{})
,Target=sequelize.define('Target',{})
varSource=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
varSource=sequelize.define('Source',{})
,Target=sequelize.define('Target',{});
varSource=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:
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.
Player.belongsTo(Team);// Will add a TeamId attribute to Player to hold the primary key value for Team
```
Observe Player is **source model** and Team is **target model**. Thus Player have information about its Team as `TeamId` making it the **source**. This relation will add a `TeamId` attribute to **source model** i.e. Player model.
#### Foreign keys
By default the foreign key for a belongsTo relation will be generated from the target model name and the target primary key name.
...
...
@@ -23,13 +25,13 @@ By default the foreign key for a belongsTo relation will be generated from the t
The default casing is `camelCase` however if the source model is configured with `underscored: true` the foreignKey will be `snake_case`.
User.belongsTo(Company,{foreignKey:'fk_company'});// Adds fk_company to User
```
#### Target keys
By default the target key for a belongsTo relation will be the target primary key. To override this behavior, use the `targetKey` option.
Its the column that will be referred from **target model**. By default the target key for a belongsTo relation will be the target model's primary key. To override this behavior, use the `targetKey` option.
If you want additional attributes in your join table, you can define a model for the join table in sequelize, before you define the association, and then tell sequelize that it should use that model for joining, instead of creating a new one:
By default the code above will add ProjectId and UserId to the UserProjects table, and _remove any previously defined primary key attribute_ - the table will be uniquely identified by the combination of the keys of the two tables, and there is no reason to have other PK columns. To enforce a primary key on the `UserProjects` model you can add it manually.
@@ -553,10 +566,10 @@ For 1:1 and 1:m associations the default option is `SET NULL` for deletion, and
Adding constraints between tables means that tables must be created in the database in a certain order, when using `sequelize.sync`. If Task has a reference to User, the User table must be created before the Task table can be created. This can sometimes lead to circular references, where sequelize cannot find an order in which to sync. Imagine a scenario of documents and versions. A document can have multiple versions, and for convenience, a document has an reference to it's current version.
```js
varDocument=this.sequelize.define('Document',{
varDocument=this.sequelize.define('document',{
author:Sequelize.STRING
})
,Version=this.sequelize.define('Version',{
,Version=this.sequelize.define('version',{
timestamp:Sequelize.DATE
})
...
...
@@ -594,7 +607,7 @@ Some times you may want to reference another table, without adding any constrain
varSeries,Trainer,Video
// Series has a trainer_id=Trainer.id foreign reference key after we call Trainer.hasMany(series)
Series=sequelize.define('Series',{
Series=sequelize.define('series',{
title:DataTypes.STRING,
sub_title:DataTypes.STRING,
description:DataTypes.TEXT,
...
...
@@ -603,19 +616,19 @@ Series = sequelize.define('Series', {
trainer_id:{
type:DataTypes.INTEGER,
references:{
model:"Trainers",
model:"trainers",
key:"id"
}
}
})
Trainer=sequelize.define('Trainer',{
Trainer=sequelize.define('trainer',{
first_name:DataTypes.STRING,
last_name:DataTypes.STRING
});
// Video has a series_id=Series.id foreign reference key after we call Series.hasOne(Video)...
Video=sequelize.define('Video',{
Video=sequelize.define('video',{
title:DataTypes.STRING,
sequence:DataTypes.INTEGER,
description:DataTypes.TEXT,
...
...
@@ -643,10 +656,10 @@ An instance can be created with nested association in one step, provided all ele
Consider the following models:
```js
varProduct=this.sequelize.define('Product',{
varProduct=this.sequelize.define('product',{
title:Sequelize.STRING
});
varUser=this.sequelize.define('User',{
varUser=this.sequelize.define('user',{
first_name:Sequelize.STRING,
last_name:Sequelize.STRING
});
...
...
@@ -692,7 +705,7 @@ return Product.create({
Let's introduce the ability to associate a project with many tags. Setting up the models could look like:
@@ -19,7 +19,7 @@ Built instances will automatically get default values when they were defined&col
```js
// first define the model
varTask=sequelize.define('Task',{
varTask=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.
@@ -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
varEmployee=sequelize.define('Employee',{
varEmployee=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
varFoo=sequelize.define('Foo',{
varFoo=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
varValidateMe=sequelize.define('Foo',{
varValidateMe=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
varPub=Sequelize.define('Pub',{
varPub=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
varBar=sequelize.define('Bar',{/* bla */},{
varBar=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
varFoo=sequelize.define('Foo',{/* bla */},{
varFoo=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.
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: