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

  • 相关阅读:
    换肤动画
    手风琴动画图
    Ajax传值原理.aspx文档
    三层框架中单表的增删改查
    用ajax传JSON数据
    利用ajax进行post传值,登录QQ和密码代码
    ado.net增删改查及存储过程
    常用的SQL语句
    金融
    写你的简历应该注意什么
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14566082.html
Copyright © 2011-2022 走看看