Professional Documents
Culture Documents
ORMs
1 // $ npm install pg
2
3 const { Client } = require('pg');
4 const connection = require('./connection.json');
5 const client = new Client(connection);
6
7 client.connect();
8
9 const query = `SELECT
10 ingredient.*, item.name AS item_name, item.type AS item_type
11 FROM
12 ingredient
13 LEFT JOIN
14 item ON item.id = ingredient.item_id
15 WHERE
16 ingredient.dish_id = $1`;
17
18 client
19 .query(query, [1])
20 .then(res => {
21 console.log('Ingredients:');
22 for (let row of res.rows) {
23 console.log(`${row.item_name}: ${row.quantity} ${row.unit}`);
24 }
25
26 client.end();
27 });
PG: Non-blocking PostgreSQL client for Node.js. Pure JavaScript and optional native libpq
bindings.
ORMs
SEQUELIZE
SEQUELIZE
1
2 const User = sequelize.define('user', {
3 // attributes
4 firstName: {
5 type: Sequelize.STRING,
6 allowNull: false
7 },
8 lastName: {
9 type: Sequelize.STRING
10 // allowNull defaults to true
11 }
12 }, {
13 // options
14 });
SEQUELIZE - Models
1 // Note: using `force: true` will drop the table if it already exists
2
3 User.sync({ force: true }).then(() => {
4 // Now the `users` table in the database corresponds to the model definition
5 return User.create({
6 firstName: 'John',
7 lastName: 'Hancock'
8 });
9 });
SEQUELIZE - Hooks
1. BelongsTo
2. HasOne
SEQUELIZE - Relations
1. HasMany
2. BelongsToMany
SEQUELIZE - Relations
1 Project.hasMany(Task)
2 Task.belongsTo(Project)
3
4 Project.create()...
5 Task.create()...
6 Task.create()...
7
8 // save them... and then:
9 project.setTasks([task1, task2]).then(() => {
10 // saved!
11 })
12
13 // ok, now they are saved... how do I get them later on?
14 project.getTasks().then(associatedTasks => {
15 // associatedTasks is an array of tasks
16 })
17
18 // You can also pass filters to the getter method.
19 // They are equal to the options you can pass to a usual finder method.
20 project.getTasks({ where: 'id > 10' }).then(tasks => {
21 // tasks with an id greater than 10 :)
22 })
23
24 // You can also only retrieve certain fields of a associated object.
25 project.getTasks({attributes: ['title']}).then(tasks => {
26 // retrieve tasks with the attributes "title" and "id"
27 })
SEQUELIZE - Queries