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

You need to sign in or sign up before continuing.
Commit 3a145c09 by Mick Hansen

Merge pull request #3838 from BridgeAR/examples

Remove outdated and not maintained examples
2 parents 8a6c1a5f 4667a4a1
/*
Title: Working with associations
This example demonstrates the use of associations.
First of all, Person is getting associated via many-to-many with other Person objects (e.g. Person.hasMany('brothers')).
Afterwards a Person becomes associated with a 'father' and a mother using a one-to-one association created by hasOneAndBelongsTo.
The last association has the type many-to-one and is defined by the function hasManyAndBelongsTo.
The rest of the example is about setting and getting the associated data.
*/
var Sequelize = require(__dirname + "/../../index")
, config = require(__dirname + "/../../spec/config/config")
, sequelize = new Sequelize(config.database, config.username, config.password, {logging: false})
, Person = sequelize.define('Person', { name: Sequelize.STRING })
, Pet = sequelize.define('Pet', { name: Sequelize.STRING })
Person.hasMany(Person, {as: 'Brothers'})
Person.hasMany(Person, {as: 'Sisters'})
Person.hasOne(Person, {as: 'Father', foreignKey: 'FatherId'})
Person.hasOne(Person, {as: 'Mother', foreignKey: 'MotherId'})
Person.hasMany(Pet)
var chainer = new Sequelize.Utils.QueryChainer
, person = Person.build({ name: 'Luke' })
, mother = Person.build({ name: 'Jane' })
, father = Person.build({ name: 'John' })
, brother = Person.build({ name: 'Brother' })
, sister = Person.build({ name: 'Sister' })
, pet = Pet.build({ name: 'Bob' })
sequelize.sync({force:true}).on('success', function() {
chainer
.add(person.save())
.add(mother.save())
.add(father.save())
.add(brother.save())
.add(sister.save())
.add(pet.save())
chainer.run().on('success', function() {
person.setMother(mother).on('success', function() { person.getMother().on('success', function(mom) {
console.log('my mom: ', mom.name)
})})
person.setFather(father).on('success', function() { person.getFather().on('success', function(dad) {
console.log('my dad: ', dad.name)
})})
person.setBrothers([brother]).on('success', function() { person.getBrothers().on('success', function(brothers) {
console.log("my brothers: " + brothers.map(function(b) { return b.name }))
})})
person.setSisters([sister]).on('success', function() { person.getSisters().on('success', function(sisters) {
console.log("my sisters: " + sisters.map(function(s) { return s.name }))
})})
person.setPets([pet]).on('success', function() { person.getPets().on('success', function(pets) {
console.log("my pets: " + pets.map(function(p) { return p.name }))
})})
}).on('failure', function(err) {
console.log(err)
})
})
\ No newline at end of file
var Sequelize = require(__dirname + "/../../index")
, config = require(__dirname + "/../../spec/config/config")
, sequelize = new Sequelize(config.database, config.username, config.password, {logging: false})
var Person = sequelize.define('Person', { name: Sequelize.STRING })
, chainer = new Sequelize.Utils.QueryChainer
sequelize.sync({force: true}).on('success', function() {
var count = 10,
queries = []
for(var i = 0; i < count; i++)
chainer.add(Person.create({name: 'someone' + (i % 3)}))
console.log("Begin to save " + count + " items!")
chainer.run().on('success', function() {
console.log("finished")
Person.count().on('success', function(count) {
console.log("Counted " + count + " elements!")
})
Person.count({where: {name: 'someone2'}}).on('success', function(count) {
console.log("Counted " + count + " elements with name = someone2!")
})
})
})
\ No newline at end of file
var Sequelize = require(__dirname + "/../../index")
, config = require(__dirname + "/../../spec/config/config")
, sequelize = new Sequelize(config.database, config.username, config.password, {logging: false})
var Person = sequelize.define('Person',
{ name: Sequelize.STRING,
age : Sequelize.INTEGER
})
, chainer = new Sequelize.Utils.QueryChainer
sequelize.sync({force: true}).on('success', function() {
var count = 10,
queries = []
for(var i = 0; i < count; i++)
chainer.add(Person.create({name: 'someone' + (i % 3), age : i+5}))
console.log("Begin to save " + count + " items!")
chainer.run().on('success', function() {
console.log("finished")
Person.max('age').on('success', function(max) {
console.log("Oldest person: " + max)
});
Person.min('age').on('success', function(min) {
console.log("Youngest person: " + min)
});
})
})
\ No newline at end of file
var Sequelize = require(__dirname + "/../../index")
, config = require(__dirname + "/../../spec/config/config")
, sequelize = new Sequelize(config.database, config.username, config.password, {logging: false, host: config.host})
, QueryChainer = Sequelize.Utils.QueryChainer
, sys = require("sys")
var Person = sequelize.define('person', { name: Sequelize.STRING })
Person.sync({force: true}).on('success', function() {
var start = Date.now()
, count = 10000
, done = 0
var createPerson = function() {
Person.create({name: 'someone'}).on('success', function() {
if(++done == count) {
var duration = (Date.now() - start)
console.log("\nFinished creation of " + count + " people. Took: " + duration + "ms (avg: " + (duration/count) + "ms)")
start = Date.now()
console.log("Will now read them from the database:")
Person.findAll().on('success', function(people) {
console.log("Reading " + people.length + " items took: " + (Date.now() - start) + "ms")
})
} else {
(done % 100 == 0) && sys.print('.')
}
}).on('failure', function(err) {
console.log(err)
})
}
console.log('Creating people :)')
for(var i = 0; i < count; i++) {
createPerson()
}
}).on('failure', function(err) {
console.log(err)
})
\ No newline at end of file
var Sequelize = require(__dirname + "/../../index")
, config = require(__dirname + "/../../spec/config/config")
, sequelize = new Sequelize(config.database, config.username, config.password, {logging: false})
var Person = sequelize.define('Person',
{ name: Sequelize.STRING,
age : Sequelize.INTEGER,
gender: Sequelize.ENUM('male', 'female')
})
, chainer = new Sequelize.Utils.QueryChainer
sequelize.sync({force: true}).on('success', function() {
var count = 10,
queries = []
for(var i = 0; i < count; i++)
chainer.add(Person.create({name: 'someone' + (i % 3), age : i+5, gender: (i % 2 == 0) ? 'male' : 'female'}))
console.log("Begin to save " + count + " items!")
chainer.run().on('success', function() {
console.log("finished")
Person.sum('age').on('success', function(sum) {
console.log("Sum of all peoples' ages: " + sum)
});
Person.sum('age', { where: { 'gender': 'male' } }).on('success', function(sum) {
console.log("Sum of all males' ages: " + sum)
});
})
})
/*
Title: Default values
This example demonstrates the use of default values for defined model fields. Instead of just specifying the datatype,
you have to pass a hash with a type and a default. You also might want to specify either an attribute can be null or not!
*/
var Sequelize = require(__dirname + "/../../index")
, config = require(__dirname + "/../../test/config")
, sequelize = new Sequelize(config.database, config.username, config.password, {logging: false})
var User = sequelize.define('User', {
name: { type: Sequelize.STRING, allowNull: false},
isAdmin: { type: Sequelize.BOOLEAN, allowNull: false, defaultValue: false }
})
, user = User.build({ name: 'Someone' })
sequelize.sync({force: true}).on('success', function() {
user.save().on('success', function(user) {
console.log("user.isAdmin should be the default value (false): ", user.isAdmin)
user.updateAttributes({ isAdmin: true }).on('success', function(user) {
console.log("user.isAdmin was overwritten to true: " + user.isAdmin)
})
})
}).on('failure', function(err) {
console.log(err)
})
\ No newline at end of file
/*jslint node:true */
"use strict";
var Sequelize = require('sequelize');
// initialize database connection
var sequelize = new Sequelize('testsequelize', 'testsequelize', 'testsequelize', {
dialect: 'postgres',
port: 5432,
define: {
freezeTableName: true
}
});
// load models
var models = [
'Trainer',
'Series',
'Video'
];
models.forEach(function(model) {
module.exports[model] = sequelize.import(__dirname + '/' + model);
});
// describe relationships
(function(m) {
m.Series.hasOne(m.Video);
m.Trainer.hasMany(m.Series);
})(module.exports);
// export connection
module.exports.sequelize = sequelize;
\ No newline at end of file
/*jslint node:true */
"use strict";
module.exports = function(sequelize, DataTypes) {
return sequelize.define('Series', {
title: {
type: DataTypes.STRING
},
sub_title: {
type: DataTypes.STRING
},
description: {
type: DataTypes.TEXT
},
// Set FK relationship (hasMany) with `Trainer`
trainer_id: {
type: DataTypes.INTEGER,
references: {
model: 'Trainer',
key: 'id'
}
}
}, {
// don't need timestamp attributes for this model
timestamps: false,
underscored: true
});
};
/*jslint node:true */
"use strict";
module.exports = function(sequelize, DataTypes) {
return sequelize.define('Trainer', {
first_name: {
type: DataTypes.STRING
},
last_name: {
type: DataTypes.STRING
}
}, {
// don't need timestamp attributes for this model
timestamps: false,
underscored: true
});
};
/*jslint node:true */
"use strict";
module.exports = function(sequelize, DataTypes) {
return sequelize.define('Video', {
title: {
type: DataTypes.STRING
},
sequence: {
type: DataTypes.INTEGER
},
description: {
type: DataTypes.TEXT
},
// set relationship (hasOne) with `Series`
series_id: {
type: DataTypes.INTEGER,
references: {
model: 'Series',
key: 'id'
}
}
}, {
// don't need timestamp attributes for this model
timestamps: false,
underscored: true
});
};
Results after syncing the dabatase
----------------------------------
After syncing the database, you'll see in the console the following:
```
Executing: CREATE TABLE IF NOT EXISTS "Trainer" ("first_name" VARCHAR(255), "last_name" VARCHAR(255), "id" SERIAL , PRIMARY KEY ("id"));
Executing: CREATE TABLE IF NOT EXISTS "Series" ("title" VARCHAR(255), "sub_title" VARCHAR(255), "description" TEXT, "trainer_id" INTEGER REFERENCES "Trainer" ("id"), "id" SERIAL , PRIMARY KEY ("id"));
Executing: CREATE TABLE IF NOT EXISTS "Video" ("title" VARCHAR(255), "sequence" INTEGER, "description" TEXT, "series_id" INTEGER REFERENCES "Series" ("id"), "id" SERIAL , PRIMARY KEY ("id"));
```
Notice in the `Video` that `series_id` field has a referential integrity to `Series`:
```
"series_id" INTEGER REFERENCES "Series" ("id")
```
This is the output when describing the table's structure of the Postgres database:
**Trainer** table:
```
testsequelize=> \d+ "Trainer";
Table "public.Trainer"
Column | Type | Modifiers |
------------+------------------------+--------------------------------------------------------+
first_name | character varying(255) | |
last_name | character varying(255) | |
id | integer | not null default nextval('"Trainer_id_seq"'::regclass) |
Indexes:
"Trainer_pkey" PRIMARY KEY, btree (id)
Referenced by:
TABLE ""Series"" CONSTRAINT "Series_trainer_id_fkey" FOREIGN KEY (trainer_id) REFERENCES "Trainer"(id)
Has OIDs: no
```
**Series** table:
```
testsequelize=> \d+ "Series";
Table "public.Series"
Column | Type | Modifiers |
-----------------+------------------------+-------------------------------------------------------+
title | character varying(255) | |
sub_title | character varying(255) | |
description | text | |
trainer_id | integer | |
id | integer | not null default nextval('"Series_id_seq"'::regclass) |
Indexes:
"Series_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"Series_trainer_id_fkey" FOREIGN KEY (trainer_id) REFERENCES "Trainer"(id)
Referenced by:
TABLE ""Video"" CONSTRAINT "Video_series_id_fkey" FOREIGN KEY (series_id) REFERENCES "Series"(id)
Has OIDs: no
```
**Video** table:
```
testsequelize=> \d+ "Video";
Table "public.Video"
Column | Type | Modifiers |
-------------+------------------------+------------------------------------------------------+
title | character varying(255) | |
sequence | integer | |
description | text | |
series_id | integer | |
id | integer | not null default nextval('"Video_id_seq"'::regclass) |
Indexes:
"Video_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"Video_series_id_fkey" FOREIGN KEY (series_id) REFERENCES "Series"(id)
Has OIDs: no
```
/*
Title: Default values
This example demonstrates the use of default values for defined model fields. Instead of just specifying the datatype,
you have to pass a hash with a type and a default. You also might want to specify either an attribute can be null or not!
*/
var Sequelize = require(__dirname + "/../../index")
, config = require(__dirname + "/../../spec/config/config")
, sequelize = new Sequelize(config.database, config.username, config.password, {logging: false})
var User = sequelize.define('User', {
name: { type: Sequelize.STRING, allowNull: false},
isAdmin: { type: Sequelize.BOOLEAN, allowNull: false, defaultValue: false }
})
, user = User.build({ name: 'Someone' })
sequelize.sync({force: true}).on('success', function() {
user.save().on('success', function(user) {
console.log("user.isAdmin should be the default value (false): ", user.isAdmin)
user.updateAttributes({ isAdmin: true }).on('success', function(user) {
console.log("user.isAdmin was overwritten to true: " + user.isAdmin)
})
})
}).on('failure', function(err) {
console.log(err)
})
\ No newline at end of file
/*
Title: Defining class and instance methods
This example shows the usage of the classMethods and instanceMethods option for Models.
*/
var Sequelize = require(__dirname + "/../../index")
, config = require(__dirname + "/../../spec/config/config")
, sequelize = new Sequelize(config.database, config.username, config.password, {logging: false})
// model definition
var Task = sequelize.define("Task", {
name: Sequelize.STRING,
deadline: Sequelize.DATE,
importance: Sequelize.INTEGER
}, {
classMethods: {
setImportance: function(newImportance, callback) {
Task.findAll().on('success', function(allTasks) {
var chainer = new Sequelize.Utils.QueryChainer
allTasks.forEach(function(task) {
chainer.add(task.updateAttributes({ importance: newImportance }))
})
chainer.run().on('success', function() {
callback && callback()
})
})
}
},
instanceMethods: {
passedDeadline: function() {
return (this.deadline < new Date())
}
}
})
// instance creation
var task1 = Task.build({
name: 'Choose a nice MySQL connector',
deadline: new Date(Date.parse("Jul 8, 2100")),
importance: 10
}),
task2 = Task.build({
name: 'Build the rest',
deadline: new Date(Date.parse("Jul 8, 2005")),
importance: 90
})
Task.sync({force: true}).on('success', function() {
new Sequelize.Utils.QueryChainer([task1.save(), task2.save()]).run().on('success', function() {
console.log("should be false: " + task1.passedDeadline())
console.log("should be true: " + task2.passedDeadline())
console.log("should be 10: " + task1.importance)
Task.setImportance(30, function() {
Task.findAll().on('success', function(tasks) {
tasks.forEach(function(task) {
console.log("should be 30: " + task.importance)
})
})
})
})
})
\ No newline at end of file
/*
Title: PostgreSQL JSON Data-Type
An example of using PostgreSQL's JSON data-type.
In this example we create a single table that can handle multiple types of different media and it's metadata.
This example uses the promise API preferred in 2.0 and above.
*/
var Sequelize = require(__dirname + "/../../index")
, config = require(__dirname + "/../../test/config/config")
, sequelize = new Sequelize(config.postgres.database, config.postgres.username, config.postgres.password, {
dialect: 'postgres',
logging: false
});
var Content = sequelize.define('Content', {
title: { type: Sequelize.STRING },
type: { type: Sequelize.STRING },
metadata: { type: Sequelize.JSON }
})
, movie = Content.build({
title: 'Grave of the Fireflies',
type: 'Movie',
metadata: {
director: 'Isao Takahata',
language: 'Japanese',
year: 1988
}
})
, episode = Content.build({
title: 'Chapter 3',
type: 'Episode',
metadata: {
season: 1,
episode: 3,
language: 'English',
seriesTitle: 'House of Cards',
genres: ['Drama', 'Political thriller']
}
});
sequelize.sync({ force: true })
.then(function() {
return sequelize.Promise.all([
movie.save(),
episode.save()
]);
})
.then(function() {
console.log('=====================================');
console.log('Searching for any content in Japanese');
console.log('-------------------------------------');
// Using nested object query syntax
return Content.find({ where: Sequelize.json({ metadata: { language: 'Japanese' } }) })
.then(function(content) {
console.log('Result:', content.dataValues);
console.log('=====================================');
})
})
.then(function() {
console.log('=====================================');
console.log('Searching for any content in English');
console.log('-------------------------------------');
// Using the postgres json syntax
return Content.find({ where: Sequelize.json("metadata->>'language'", 'English') })
.then(function(content) {
console.log('Result:', content.dataValues);
console.log('=====================================');
})
})
.then(function() {
console.log('===========================================');
console.log('Searching for series named "House of Cards"');
console.log('-------------------------------------------');
return Content.find({ where: Sequelize.json('metadata.seriesTitle', 'House of Cards') })
.then(function(content) {
console.log('Result:', content.dataValues);
console.log('===========================================');
})
});
\ No newline at end of file
var Sequelize = require(__dirname + "/../../index")
, config = require(__dirname + "/../../spec/config/config")
, sequelize = new Sequelize(config.database, config.username, config.password, {
// use other database server or port
host: 'my.srv.tld',
port: 12345,
// disable logging
logging: false
})
, Smth = sequelize.define('Smth', {foo: Sequelize.STRING})
sequelize.sync({force: true}).on('success', function() {
console.log('Hey we established the connection successfully! Woot!')
}).on('failure', function(err) {
console.log(err)
})
\ No newline at end of file
module.exports = function(sequelize, DataTypes) {
return sequelize.define("Project", {
name: DataTypes.STRING,
description: DataTypes.TEXT
})
}
\ No newline at end of file
module.exports = function(sequelize, DataTypes) {
return sequelize.define("Task", {
name: DataTypes.STRING,
deadline: DataTypes.DATE,
importance: DataTypes.INTEGER
})
}
\ No newline at end of file
var Sequelize = require(__dirname + "/../../index")
, config = require(__dirname + "/../../spec/config/config")
, sequelize = new Sequelize(config.database, config.username, config.password, {logging: false})
, Project = sequelize.import(__dirname + "/Project")
, Task = sequelize.import(__dirname + "/Task")
Project.hasMany(Task)
Task.belongsTo(Project)
sequelize.sync({force: true}).on('success', function() {
Project
.create({ name: 'Sequelize', description: 'A nice MySQL ORM for NodeJS' })
.on('success', function(project) {
Task.create({ name: 'Choose a nice MySQL connector', deadline: new Date(), importance: 10 })
.on('success', function(task1) {
Task.create({ name: 'Build the rest', deadline: new Date(), importance: 90 })
.on('success', function(task2) {
project.setTasks([task1, task2]).on('success', function(tasks) {
console.log(project)
console.log(tasks)
})
})
})
})
})
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!