zoukankan      html  css  js  c++  java
  • [Node.js] Sequelize Intro

    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

  • 相关阅读:
    Linux安全-通过修改/etc/hosts.deny拒绝远程ssh暴力破解
    JS-二进制的处理者:Blob
    JS-二进制数据缓冲区ArrayBuffer
    axio源码分析
    【js】appendChild()具有移动性
    js实现-二进制数据转换为blob
    实现点击下载到本地的功能
    memo、useMemo、useCallback
    memoization缓存优化
    什么是纯函数?
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14566082.html
Copyright © 2011-2022 走看看