• nodejs 最受欢迎的orm sequelize


    传送门

    # 视频教程
    https://nodelover.me/course/sequelize/
    
    # 官方文档
    http://docs.sequelizejs.com/manual/tutorial/models-definition.html
    
    # sequelize-cli 文档
    http://docs.sequelizejs.com/manual/tutorial/migrations.html#the-cli

    数据库连接,以mysql为例

    const Sequelize = require('sequelize');
    
    const connect = new Sequelize('database', 'username', 'password', {
        host: 'localhost',
        port: 3306,
        dialect: 'mysql',
        pool: {
            max: 5,
            min: 0,
            acquire: 30000,
            idle: 10000
        },
    });
    
    connect.authenticate().then(() => {
        console.log('Connection has been established successfully.');
    })
    .catch(err => {
        console.error('Unable to connect to the database:', err);
    });

    model的创建和同步数据库

    // 模型定义API:http://docs.sequelizejs.com/manual/tutorial/models-definition.html
    const User = sequelize.define('user', {
        firstName: { type: Sequelize.STRING },
        lastName: { type: Sequelize.STRING },
    }, {
        // 省略 createdAt 和 updateAt
        timestamps: false
    });
    
    // 第一次没有表的时候需要同步来创建
    // http://docs.sequelizejs.com/manual/tutorial/instances.html
    // 官方还有两种额外的做法,一种是先build一个实例,然后save(),一种是直接create
    sequelize.sync({
        force: true
    }).then(() => {
        return User.create({
            firstName: 'John',
            lastName: 'Hancock'
        })
    }).then(() => {
        return User.find({
            where: {
                firstName: 'John'
            }
        })
    }).then(console.log)

    sequelize-cli 的安装和使用

    http://docs.sequelizejs.com/manual/tutorial/migrations.html#the-cli

    $ npm i sequelize-cli -g
    $ sequelize init
    $ sequelize model:generate --name User --attributes firstName:string,lastName:string,email:string
  • 相关阅读:
    LeetCode 501. 二叉搜索树中的众数
    LeetCode 404.左叶子之和
    LeetCode 450. 删除二叉搜索树中的节点
    LeetCode 437. 路径总和 III
    LeetCode 429. N 叉树的层序遍历
    LeetCode 213. 打家劫舍 II
    LeetCode 337. 打家劫舍 III
    LeetCode 198. 打家劫舍
    LeetCode 235. 二叉搜索树的最近公共祖先
    LeetCode 230. 二叉搜索树中第K小的元素
  • 原文地址:https://www.cnblogs.com/CyLee/p/9752458.html
Copyright © 2020-2023  润新知