官术网_书友最值得收藏!

  • Node.js 6.x Blueprints
  • Fernando Monteiro
  • 237字
  • 2021-07-14 10:35:06

Creating a User scheme

With the help of Sequelize-cli we will create a simple scheme for application users:

Open terminal/shell at the root project folder and type the following command:

 sequelize model:create --name User --attributes "name:string, email:string"

You will see the following output on your terminal window:

Sequelize [Node: 6.3.0, CLI: 2.3.1, ORM: 3.19.3]
Loaded configuration file "config/config.json".
Using environment "development".
Using gulpfile /usr/local/lib/node_modules/sequelize- cli/lib/gulpfile.js
Starting 'model:create'...
Finished 'model:create' after 13 ms

Let's check the user model file present at: models/User.js, here add sequelize using the define() function to create the User scheme:

      'use strict'; 
      module.exports = function(sequelize, DataTypes) { 
        var User = sequelize.define('User', { 
          name: DataTypes.STRING, 
          email: DataTypes.STRING 
        },
       { 
          classMethods: { 
           associate: function(models) { 
              // associations can be defined here 
           } 
        } 
       }); 
       return User; 
       }; 

Note that this command created the User.js file within the models folder and also created a migration file containing a hash and the name of the operation to be performed on the database within the migrations folder.

This file contains the boilerplate necessary for creation of the User table in the database.

      'use strict'; 
       module.exports = { 
        up: function(queryInterface, Sequelize) { 
          return queryInterface.createTable('Users', { 
            id: { 
              allowNull: false, 
              autoIncrement: true, 
              primaryKey: true, 
              type: Sequelize.INTEGER 
            }, 
            name: { 
                type: Sequelize.STRING 
            }, 
            email: { 
              type: Sequelize.STRING 
            }, 
            createdAt: { 
              allowNull: false, 
              type: Sequelize.DATE 
            }, 
            updatedAt: { 
               allowNull: false, 
               type: Sequelize.DATE 
            } 
          }); 
        }, 
        down: function(queryInterface, Sequelize) { 
            return queryInterface.dropTable('Users'); 
        } 
      }; 
主站蜘蛛池模板: 德格县| 长汀县| 云浮市| 灵寿县| 保山市| 宾阳县| 慈溪市| 澜沧| 临武县| 庆元县| 安康市| 祁东县| 鄯善县| 嘉禾县| 庐江县| 治县。| 介休市| 鲁甸县| 大兴区| 泌阳县| 濮阳县| 泽库县| 福安市| 阜阳市| 淮北市| 兰州市| 色达县| 茂名市| 石渠县| 泰和县| 东港市| 沙河市| 桓仁| 尖扎县| 丁青县| 溆浦县| 扶绥县| 濉溪县| 米林县| 宣城市| 日土县|