nodejs--数据库模块

1、简述

Sequelize是用于Postgres,MySQL,MariaDB,SQLite和Microsoft SQL Server的基于约定的Node.js ORM。

2、入门

(1)连接mysql
config.js实际上是一个简单的配置文件:

var config = {
    database: 'test', // 使用哪个数据库
    username: 'www', // 用户名
    password: 'www', // 口令
    host: 'localhost', // 主机名
    port: 3306 // 端口号,MySQL默认3306
};

module.exports = config;

在app.js中操作数据库

const Sequelize = require('sequelize');
const config = require('./config');

var sequelize = new Sequelize(config.database, config.username, config.password, {
    host: config.host,
    dialect: 'mysql',
    pool: {
        max: 5,   // 连接池中最大连接数量
        min: 0,   // 连接池中最小连接数量
        idle: 30000 // 如果一个线程 10 秒钟内没有被使用过的话,那么就释放线程   
    }
});

(2)模型User,告诉Sequelize如何映射数据库表:

// user.js
 var Sequelize = require('sequelize');
var sequelize = require('./db');
 
// 创建 model
    const User = sequelize.define('user', {
        userName: {
            type: Sequelize.STRING, // 指定值的类型
            field: 'user_name' // 指定存储在表中的键名称
        },
        // 没有指定 field,表中键名称则与对象键名相同,为 email
        email: {
            type: Sequelize.STRING
        }
    }, {
        // 如果为 true 则表的名称和 model 相同,即 user
        // 为 false MySQL创建的表名称会是复数 users
        // 如果指定的表名称本就是复数形式则不变
        freezeTableName: false
    });
//如果不存在就创建此表
 var user = User.sync({ force: false });

// 添加新用户
exports.addUser = function(userName, email) {
    // 向 user 表中插入数据
    return User.create({
        userName: userName,
        email: email
    });
};

测试函数

//testUser.js
var user = require('./user'); //引入模型
 
// 添加用户
user.addUser('jack', 'jack@163.com').then(function() {
    // 查询新添加的用户
    return user.findOne({ where: { user_name: userName }}) 
    
}).then(function(user) {
    console.log('****************************');
    console.log('user name: ', user.userName);
    console.log('user email: ', user.email);
});

(3)添加数据

(async () => {
    var user = await User.create({
       userName: "kk",
        email: "1234@123"
    });
    console.log('created: ' + JSON.stringify(user));
})();

(4)修改数据

(async () => {
	var updateDict = {
	name:'newName', 
	emil: '123@12'
	}
    var user = await User.update({
       where:{
       		name: "kk",
       }
    });
    console.log('created: ' + JSON.stringify(user));
})();

(5)删除数据

(async () => {
    var user = await User.destroy({
       where:{
       		name: "kk",
       }
    });
    console.log('created: ' + JSON.stringify(user));
})();

(6)查询数据
使用findAll或findOne

(async () => {
    var user = await User.findAll({
        where: {
            name: 'Gaffey'
        }
    });
    console.log(`find ${user.length} users:`);
    for (let p of user) {
        console.log(JSON.stringify(p));
    }
})();

学习链接:https://www.liaoxuefeng.com/wiki/1022910821149312/1101571555324224
https://www.cnblogs.com/lyc1226/p/12113199.html
https://blog.csdn.net/njweiyukun/article/details/103267027

3、原始查询

const users = await sequelize.query("SELECT * FROM `users`", { type: QueryTypes.SELECT });
// 我们不需要在这里分解结果 - 结果会直接返回

学习链接:https://github.com/demopark/sequelize-docs-Zh-CN/blob/master/core-concepts/raw-queries.md

4、事务

非托管事务: 提交和回滚事务应由用户手动完成(通过调用适当的 Sequelize 方法).

托管事务: 如果引发任何错误,Sequelize 将自动回滚事务,否则将提交事务. 另外,如果启用了CLS(连续本地存储),则事务回调中的所有查询将自动接收事务对象.
(1)非托管事务
const t = await sequelize.transaction(); //开启事务
await t.commit(); //提交事务
await t.rollback(); //回滚事务

// 首先,我们开始一个事务并将其保存到变量中
const t = await sequelize.transaction();

try {

  // 然后,我们进行一些调用以将此事务作为参数传递:

  const user = await User.create({
    firstName: 'Bart',
    lastName: 'Simpson'
  }, { transaction: t });

  await user.addSibling({
    firstName: 'Lisa',
    lastName: 'Simpson'
  }, { transaction: t });

  // 如果执行到此行,且没有引发任何错误.
  // 我们提交事务.
  await t.commit();

} catch (error) {

  // 如果执行到达此行,则抛出错误.
  // 我们回滚事务.
  await t.rollback();

}

(2)托管事务
const result = await sequelize.transaction(async (t) => {

// 如果执行到此行,则表示事务已成功提交,result是事务返回的结果
// result 就是从事务回调中返回的结果(在这种情况下为 user)
} catch (error) {
// 如果执行到此,则发生错误.
// 该事务已由 Sequelize 自动回滚!
}

const result = await sequelize.transaction(async (t) => {

    const user = await User.create({
      firstName: 'Abraham',
      lastName: 'Lincoln'
    }, { transaction: t });

    await user.setShooter({
      firstName: 'John',
      lastName: 'Boothe'
    }, { transaction: t });

    return user;

  });

  // 如果执行到此行,则表示事务已成功提交,`result`是事务返回的结果
  // `result` 就是从事务回调中返回的结果(在这种情况下为 `user`)

} catch (error) {

  // 如果执行到此,则发生错误.
  // 该事务已由 Sequelize 自动回滚!

}

学习链接:https://github.com/demopark/sequelize-docs-Zh-CN/blob/master/other-topics/transactions.md

其他操作学习链接:https://github.com/demopark/sequelize-docs-Zh-CN

5、多条件查询

(1)例如

Post.findAll({
  where: {
    authorId: 12
    status: 'active'
  }
});
const { Op } = require("sequelize");
Post.findAll({
  where: {
    [Op.and]: [
      { authorId: 12 },
      { status: 'active' }
    ]
  }
});

(2)操作符

const { Op } = require("sequelize");
Post.findAll({
  where: {
    [Op.and]: [{ a: 5 }, { b: 6 }],            // (a = 5) AND (b = 6)
    [Op.or]: [{ a: 5 }, { b: 6 }],             // (a = 5) OR (b = 6)
    someAttribute: {
      // 基本
      [Op.eq]: 3,                              // = 3
      [Op.ne]: 20,                             // != 20
      [Op.is]: null,                           // IS NULL
      [Op.not]: true,                          // IS NOT TRUE
      [Op.or]: [5, 6],                         // (someAttribute = 5) OR (someAttribute = 6)

      // 使用方言特定的列标识符 (以下示例中使用 PG):
      [Op.col]: 'user.organization_id',        // = "user"."organization_id"

      // 数字比较
      [Op.gt]: 6,                              // > 6
      [Op.gte]: 6,                             // >= 6
      [Op.lt]: 10,                             // < 10
      [Op.lte]: 10,                            // <= 10
      [Op.between]: [6, 10],                   // BETWEEN 6 AND 10
      [Op.notBetween]: [11, 15],               // NOT BETWEEN 11 AND 15

      // 其它操作符

      [Op.all]: sequelize.literal('SELECT 1'), // > ALL (SELECT 1)

      [Op.in]: [1, 2],                         // IN [1, 2]
      [Op.notIn]: [1, 2],                      // NOT IN [1, 2]

      [Op.like]: '%hat',                       // LIKE '%hat'
      [Op.notLike]: '%hat',                    // NOT LIKE '%hat'
      [Op.startsWith]: 'hat',                  // LIKE 'hat%'
      [Op.endsWith]: 'hat',                    // LIKE '%hat'
      [Op.substring]: 'hat',                   // LIKE '%hat%'
      [Op.iLike]: '%hat',                      // ILIKE '%hat' (不区分大小写) (仅 PG)
      [Op.notILike]: '%hat',                   // NOT ILIKE '%hat'  (仅 PG)
      [Op.regexp]: '^[h|a|t]',                 // REGEXP/~ '^[h|a|t]' (仅 MySQL/PG)
      [Op.notRegexp]: '^[h|a|t]',              // NOT REGEXP/!~ '^[h|a|t]' (仅 MySQL/PG)
      [Op.iRegexp]: '^[h|a|t]',                // ~* '^[h|a|t]' (仅 PG)
      [Op.notIRegexp]: '^[h|a|t]',             // !~* '^[h|a|t]' (仅 PG)

      [Op.any]: [2, 3],                        // ANY ARRAY[2, 3]::INTEGER (仅 PG)

      // 在 Postgres 中, Op.like/Op.iLike/Op.notLike 可以结合 Op.any 使用:
      [Op.like]: { [Op.any]: ['cat', 'hat'] }  // LIKE ANY ARRAY['cat', 'hat']

      // 还有更多的仅限 postgres 的范围运算符,请参见下文
    }
  }
});

6、排序和分组

排序

Foo.findOne({
  order: [
    // 将返回 `name`
    ['name'],
    // 将返回 `username` DESC
    ['username', 'DESC'],
    // 将返回 max(`age`)
    sequelize.fn('max', sequelize.col('age')),
    // 将返回 max(`age`) DESC
    [sequelize.fn('max', sequelize.col('age')), 'DESC'],
    // 将返回 otherfunction(`col1`, 12, 'lalala') DESC
    [sequelize.fn('otherfunction', sequelize.col('col1'), 12, 'lalala'), 'DESC'],
    // 将返回 otherfunction(awesomefunction(`col`)) DESC, 这种嵌套可能是无限的!
    [sequelize.fn('otherfunction', sequelize.fn('awesomefunction', sequelize.col('col'))), 'DESC']
  ]
});

分组

Project.findAll({ group: 'name' });
// 生成 'GROUP BY name'

7、限制与分页

// 提取10个实例/行
Project.findAll({ limit: 10 });

// 跳过8个实例/行
Project.findAll({ offset: 8 });

// 跳过5个实例,然后获取5个实例
Project.findAll({ offset: 5, limit: 5 });

学习链接:https://github.com/demopark/sequelize-docs-Zh-CN/blob/master/core-concepts/model-querying-basics.md

8、查找器

findByPk 方法使用提供的主键从表中仅获得一个条目.
findOne 方法获得它找到的第一个条目(它可以满足提供的可选查询参数).
学习链接:https://github.com/demopark/sequelize-docs-Zh-CN/blob/master/core-concepts/model-querying-finders.md

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值