Note:
$>means command line input
Dependencies to use Sequelize
$> npm install --save sequelize pg pg-hstore
Must create the DB first
$> createdb my-music
| // Product Model definition, called 'product' and associated with table 'products' | |
| var Product = this.sequelize.define('product', { | |
| title: Sequelize.STRING | |
| }); | |
| // User Model definition, called 'user' and associated with table 'users' | |
| var User = this.sequelize.define('user', { | |
| first_name: Sequelize.STRING, | |
| last_name: Sequelize.STRING | |
| }); |
| const express = require('express') | |
| const app = express() | |
| const crypto = require('crypto') | |
| const secretKey = '<your secret key>' | |
| const bodyParser = require('body-parser') | |
| app.use('/webhooks', bodyParser.raw({ type: 'application/json' })) | |
| app.use(bodyParser.json()) | |
| app.post('/webhooks/orders/create', async (req, res) => { |
| CREATE OR REPLACE FUNCTION jsonb_merge(left JSONB, right JSONB) RETURNS JSONB AS $$ | |
| var mergeJSON = function (target, add) { | |
| function isObject(obj) { | |
| if (typeof obj == "object") { | |
| for (var key in obj) { | |
| if (obj.hasOwnProperty(key)) { | |
| return true; // search for first object prop | |
| } | |
| } |
| # 1: Use node 6 as base: | |
| FROM node:6-alpine | |
| # 2: Download+Install PhantomJS, as the npm package 'phantomjs-prebuilt' won't work on alpine! | |
| # See https://github.com/dustinblackman/phantomized | |
| RUN set -ex \ | |
| && apk add --no-cache --virtual .build-deps ca-certificates openssl \ | |
| && wget -qO- "https://github.com/dustinblackman/phantomized/releases/download/2.1.1/dockerized-phantomjs.tar.gz" | tar xz -C / \ | |
| && npm install -g phantomjs \ | |
| && apk del .build-deps |
When querying your database in Sequelize, you'll often want data associated with a particular model which isn't in the model's table directly. This data is usually typically associated through join tables (e.g. a 'hasMany' or 'belongsToMany' association), or a foreign key (e.g. a 'hasOne' or 'belongsTo' association).
When you query, you'll receive just the rows you've looked for. With eager loading, you'll also get any associated data. For some reason, I can never remember the proper way to do eager loading when writing my Sequelize queries. I've seen others struggle with the same thing.
Eager loading is confusing because the 'include' that is uses has unfamiliar fields is set in an array rather than just an object.
So let's go through the one query that's worth memorizing to handle your eager loading.