0%

13. ORM

ORMS

Object Relational Mappings

Sequelize

model/user.js

not need to define model.js by ourselves

  • table not exists: create table/ exists: send the related table

models/task.js

connecting db with new Sequelize
.readditSync(__dirname) : return array of files in __dirname
// [index.js, task.js, user.js, .hide]
.filter(file => {
return (file.indexOf(‘.’) !== 0) && (file !== ‘index.js’) && (file.slice(-3) === ‘.js’);
// [task.js, user.js]
.forEach(file => {
const model = require(path.join(__dirname, file))
// create absolute path to the file
(sequelize, Sequelize.DataTypes);
// requiring models/task.js function
db[model.name] = model
// model: task / user
// each file will be the model object
db.sequelize = sequelize;
db.Sequelize = Sequelize;
// take the code and put it individually
// leave this code without changing anything in this file
module.exports = db
exports db with passing db

👇

index.js

  • set-up everything in the db perfectly and then connect to the client

router.js

not changed

controllers/user.js

models/user.js

models/task.js

— complete declare, now run —

models/index.js

mkcd [dir]
npm init -y
touch [index.js] [router.js]
npm i sequelize koa koa-router

create table

get the model : model/index.js, createStudent -> not view, create template with the data

get student by id, bodyparser -> router.post

* npm weekly downloads : >= 7M *