[Node.js] Sequelize Intro - 1
Intro to Object-Relational Maps (ORM)
We'll be using an ORM called Sequelize to manage the connection to our database. We'll cover the basics in this concept, but Sequelize is a powerful tool and is extremely well documented at http://docs.sequelizejs.com/
Models
A model is the data representation of some group of data. In object-oriented programing terms, a model is an object and is represented by a new class. It should usually represent a noun such as a user, a feed item, an order, etc. We use the @Table
decorator and extend the base sequelize Model
class to link our model to our database table.
Parameters
The model contains instance parameters. These can be other models or primitive fields. We use the @Column
decorator to link our parameters to the table columns. The bang symbol !
specifies if the field in the table can be null. Sequelize handles the datatype mappings from TypeScript types to Postgres column datatypes.
Read more at the Sequelize docs entry on models.
Model:
import {Table, Column, Model, HasMany, PrimaryKey, CreatedAt, UpdatedAt, ForeignKey} from 'sequelize-typescript'; import { User } from '../../users/models/User'; @Table export class FeedItem extends Model<FeedItem> { @Column public caption!: string; @Column public url!: string; @Column @CreatedAt public createdAt: Date = new Date(); @Column @UpdatedAt public updatedAt: Date = new Date(); }
Usage:
const items = await FeedItem.findAndCountAll({ order: [["id", "DESC"]] }); const feed = await FeedItem.findByPk(id); const item = await new FeedItem({ caption: caption, url: fileName, }); const saved_item = await item.save();
Decorators
The Decorators (also known as Annotations) mentioned in this video are a feature of the sequelize-typescript package which allows us to link database features with our models. We exemplify this using the @CreatedAt
and @UpdatedAt
. This will set the option in the Postgres database to automatically set the date when any row is created, or updated and is useful when sorting and filtering our data.
Read more and view complete details on the model definition in the sequelize-typescript docs
相关文章
- js笔记——js数据类型转换
- Swoole 是 PHP 中的 Node.js?
- Node.js进程管理之Process模块
- Node.js文件操作二
- node.js module初步理解
- [Node.js] Add node.js command line to global
- [Node.js] Sequelize Intro - 2 Migrations
- [WASM] Run WebAssembly in Node.js using the node-loader
- [Whole Web, Node.js, PM2] Restarting your node.js app on code change using pm2
- 使用 Node.js 搭建API 网关
- [Node.js] Sequelize Intro - 1
- Node Js And The New Web Front End
- js日期格式化函数示例:将日期时间格式化成yyyy-mm-dd hh:ii:ss格式
- [FE] nvm-windows: Microsoft/NPM/Google 推荐 Windows 的 Node.js 版本管理器
- Node.js 的单线程事件驱动模型和内置的线程池模型
- 图片处理工具GraphicsMagick介绍安装使用:GraphicsMagick图像处理系统Node.js gm模块处理图片(缩略图,加水印,裁剪图片)
- 慕课网前端项目:Vue2.0+Node.js+MongoDB全栈打造商城系统 笔记 整理【4/18】
- Node.js: node-redis.js客户端
- js实现搜索数组中元素插入的位置
- 阅读zepto.js的core中的Core methods
- Node.js学习笔记——mongoDB