node.js backend of sequelize

node.js backend of sequelize

In simple terms, node.js is running in the back end of javascript, backend definitely need to access the database, and the object is to introduce today we can so you do not need the pain to write sql statement, ORM framework --sequelize improve efficiency.

Ready to work

installation

First, create a new folder sequelize_demo, open a terminal (default already node environment), input npm init, this will initialize this folder and generate a .json file, the way to enter default.

Next, install the express framework:

$ npm install express --save

And then the installation frame sequelize mysql drive:

$ npm install --save sequelize
$ npm install --save mysql2

ok, the installation is complete

Create a file

Resolved to create the file that we need to use the file directory as follows ~

Connect to the database

Then start connecting to the database, open db.js

//db.js
var Sequelize = require('sequelize');

//四个参数分别是 数据库名称,用户名,密码,配置

module.exports = new Sequelize('farmer', 'root', '123456', { //换成自己的数据库
    host: 'localhost', // 数据库地址
    dialect: 'mysql', // 指定连接的数据库类型
    pool: {
        max: 5, // 连接池中最大连接数量
        min: 0, // 连接池中最小连接数量
        idle: 10000 // 如果一个线程 10 秒钟内没有被使用过的话,那么就释放线程
    }
});

Model file user.js, this model is used and the database tables correspond to a model represents a form, we write a good model, allowing sequelize automatically create database tables for us, very convenient. Use define function to create a model

// 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
    });
};

Then enter the terminal, start the service node app.js, open the database will find the table already created. The final createdAt and updatedAt sequelize is automatically added, of course, do not want to be like this:

  // 不要添加时间戳属性 (updatedAt, createdAt)
  timestamps: false,

Then write a test function testUser.js, where we will be happy to use sequelize packaged functions to manipulate matter, sql statement and say goodbye!

Commonly used functions such as find, findAll, create, a detailed look at the official document https://sequelize.org/v5/manual/models-usage.html

//testUser.js
var user = require('./user'); //引入模型
 
// 添加用户
user.addUser('jack', '[email protected]').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);
});

Enter the terminal, run testUser

node testUser.js

Open the database will find the data has been inserted into the database ~

Guess you like

Origin www.cnblogs.com/lyc1226/p/12113199.html