Sequelize-nodejs-1-getting started

本文详细介绍Sequelize ORM的基本概念、安装配置方法及如何在Node.js中建立数据库连接。Sequelize支持多种数据库方言,如PostgreSQL、MySQL、SQLite和MSSQL,并提供了事务、关系和读复制等功能。文章还解释了如何使用Promise进行异步控制流,以及如何测试数据库连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Sequelize is a promise-based ORM for Node.js v4 and up. It supports the dialects PostgreSQL, MySQL, SQLite and MSSQL and features solid transaction support, relations, read replication and more.

Sequelize是一种基于promise的ORM(对象关系映射),支持nodejs版本4及以上。它支持PostgreSQL、MySQL、SQLite和MSSQL语言,并具有可靠的事务支持、关系、读复制等特性。

 

安装:

// Using NPM
$ npm install --save sequelize
$ npm install --save mysql2

我使用的是mysql,所以安装的是上面两个模块

⚠️要安装mysql2,否则报错:

Error: Please install mysql2 package manually

 相应的其他对应安装:

$ npm install --save pg pg-hstore
$ npm install --save mysql2
$ npm install --save sqlite3
$ npm install --save tedious // MSSQL

 

Setting up a connection

Sequelize will setup a connection pool on initialization so you should ideally only ever create one instance per database if you're connecting to the DB from a single process. If you're connecting to the DB from multiple processes, you'll have to create one instance per process, but each instance should have a maximum connection pool size of "max connection pool size divided by number of instances". So, if you wanted a max connection pool size of 90 and you had 3 worker processes, each process's instance should have a max connection pool size of 30.

Sequelize将在初始化时设置一个连接池,因此理想情况下,如果从单个进程连接到数据库,那么每个数据库应该只创建一个实例。如果要从多个进程连接到数据库,必须为每个进程创建一个实例,但是每个实例的最大连接池大小应该是“最大连接池大小除以实例数量”。因此,如果您希望最大连接池大小为90,并且您有3个工作进程,那么每个进程的实例的最大连接池大小应该为30。

const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: 'mysql'|'sqlite'|'postgres'|'mssql',
  operatorsAliases: false,

  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  },

  // SQLite only
  storage: 'path/to/database.sqlite'
});

// Or you can simply use a connection uri
const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');

 

Test the connection

You can use the .authenticate() function like this to test the connection.

sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });

 

Promises (如果不了解什么是promise,可以看本博客js同步-异步-回调 )

Sequelize uses Bluebird promises to control async control-flow.

Note: Sequelize use independent copy of Bluebird instance. You can access it using Sequelize.Promise if you want to set any Bluebird specific options

If you are unfamiliar with how promises work, don't worry, you can read up on them here.

Basically, a promise represents a value which will be present at some point - "I promise you I will give you a result or an error at some point". This means that

// DON'T DO THIS
user = User.findOne()
console.log(user.get('firstName'));

will never work! This is because user is a promise object, not a data row from the DB. The right way to do it is:

User.findOne().then(user => {
  console.log(user.get('firstName'));
});

When your environment or transpiler supports async/await this will work but only in the body of an asyncfunction:

user = await User.findOne()
console.log(user.get('firstName'));

Once you've got the hang of what promises are and how they work, use the bluebird API reference as your go-to tool. In particular, you'll probably be using .all a lot.

 

 

 


 

转载于:https://www.cnblogs.com/wanghui-garcia/p/10045728.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值