sequelize-入门

来源:互联网 发布:windows vista开不了机 编辑:程序博客网 时间:2024/06/07 05:02

建立连接

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

const Sequelize = require('sequelize');const sequelize = new Sequelize('database', 'username', 'password', {  host: 'localhost',  dialect: 'mysql'|'sqlite'|'postgres'|'mssql',  pool: {    max: 5,    min: 0,    acquire: 30000,    idle: 10000  },  // SQLite only  storage: 'path/to/database.sqlite'});// Or you can simply use a connection uriconst sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');

Sequelize构造函数需要通过API参考提供的一整套选项

测试连接

您可以使用这样的.authenticate()功能来测试连接。

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

你的第一个模型

模型被定义为sequelize.define('name', {attributes}, {options})

const User = sequelize.define('user', {  firstName: {    type: Sequelize.STRING  },  lastName: {    type: Sequelize.STRING  }});// force: true will drop the table if it already existsUser.sync({force: true}).then(() => {  // Table created  return User.create({    firstName: 'John',    lastName: 'Hancock'  });});

您可以在Model API参考中阅读更多关于创建模型的信息

你的第一个查询

User.findAll().then(users => {  console.log(users)})

你可以阅读更多关于车型取景功能,如.findAll()数据检索或如何做这样的具体问题WHERE,并JSONB查询

应用广泛的模型选项

Sequelize构造函数会使用一个define选项作为所有已定义模型的默认选项。

const sequelize = new Sequelize('connectionUri', {  define: {    timestamps: false // true by default  }});const User = sequelize.define('user', {}); // timestamps is false by defaultconst Post = sequelize.define('post', {}, {  timestamps: true // timestamps will now be true});

Promises

Sequelize使用Bluebird Promises控制异步控制流。

注意: Sequelize使用Bluebird实例的独立副本。Sequelize.Promise如果你想设置任何Bluebird特定的选项,你可以使用它

如果你不熟悉promises如何工作,不要担心,你可以在这里阅读

基本上,一个promise代表了某种程度上会存在的价值 - “我保证,我会在某个时候给你一个结果或一个错误”。这意味着

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

将永远不会工作!这是因为userpromise对象,而不是来自数据库的数据行。正确的做法是:

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

当你的环境或转译器支持 async/await这将工作,但只在一个 async函数的主体

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

一旦掌握了promise以及工作方式,就可以使用蓝鸟API参考作为您首选工具。特别是,你可能会用.all很多。

原创粉丝点击