启动服务器后,带有sequelize的Node.js无法在mysql工作台中创建表

时间:2019-03-02 09:42:22

标签: mysql node.js sequelize.js

我开始学习如何使用Nodejs使用ExpressjsSequelizeMySQLMysqlworkbench构建Rest API。 我的问题:启动服务器后,该表不是由Sequelize创建的,Mysqlworkbench中也没有任何表。只是此消息出现在下面...感谢您的任何指导或帮助:-

Sequelize {
  options:
   { dialect: 'mysql',
     dialectModulePath: null,
     host: 'localhost',
     protocol: 'tcp',
     define: {},
     query: {},
     sync: {},
     timezone: '+00:00',
     logging: [Function: bound consoleCall],
     omitNull: false,
     native: false,
     replication: false,
     ssl: undefined,
     pool: {},
     quoteIdentifiers: true,
     hooks: {},
     retry: { max: 5, match: [Array] },
     transactionType: 'DEFERRED',
     isolationLevel: null,
     databaseVersion: 0,
     typeValidation: false,
     benchmark: false,
     operatorsAliases: false },
  config:
   { database: 'node',
     username: 'root',
     password: '1234567890',
     host: 'localhost',
     port: 3306,
     pool: {},
     protocol: 'tcp',
     native: false,
     ssl: undefined,
     replication: false,
     dialectModulePath: null,
     keepDefaultTimezone: undefined,
     dialectOptions: undefined },
  dialect:
   MysqlDialect {
     sequelize: [Circular],
     connectionManager:
      ConnectionManager {
        sequelize: [Circular],
        config: [Object],
        dialect: [Circular],
        versionPromise: null,
        dialectName: 'mysql',
        pool: [Object],
        lib: [Object] },
     QueryGenerator:
      { dialect: 'mysql',
        OperatorMap: [Object],
        createSchema: [Function: createSchema],
        showSchemasQuery: [Function: showSchemasQuery],
        versionQuery: [Function: versionQuery],
        createTableQuery: [Function: createTableQuery],
        showTablesQuery: [Function: showTablesQuery],
        addColumnQuery: [Function: addColumnQuery],
        removeColumnQuery: [Function: removeColumnQuery],
        changeColumnQuery: [Function: changeColumnQuery],
        renameColumnQuery: [Function: renameColumnQuery],
        handleSequelizeMethod: [Function: handleSequelizeMethod],
        _toJSONValue: [Function: _toJSONValue],
        upsertQuery: [Function: upsertQuery],
        deleteQuery: [Function: deleteQuery],
        showIndexesQuery: [Function: showIndexesQuery],
        showConstraintsQuery: [Function: showConstraintsQuery],
        removeIndexQuery: [Function: removeIndexQuery],
        attributeToSQL: [Function: attributeToSQL],
        attributesToSQL: [Function: attributesToSQL],
        quoteIdentifier: [Function: quoteIdentifier],
        _checkValidJsonStatement: [Function: _checkValidJsonStatement],
        jsonPathExtractionQuery: [Function: jsonPathExtractionQuery],
        _getForeignKeysQueryFields: [Function: _getForeignKeysQueryFields],
        getForeignKeysQuery: [Function: getForeignKeysQuery],
        getForeignKeyQuery: [Function: getForeignKeyQuery],
        dropForeignKeyQuery: [Function: dropForeignKeyQuery],
        _templateSettings: [Object],
        options: [Object],
        extractTableDetails: [Function: extractTableDetails],
        addSchema: [Function: addSchema],
        dropSchema: [Function: dropSchema],
        describeTableQuery: [Function: describeTableQuery],
        dropTableQuery: [Function: dropTableQuery],
        renameTableQuery: [Function: renameTableQuery],
        insertQuery: [Function: insertQuery],
        bulkInsertQuery: [Function: bulkInsertQuery],
        updateQuery: [Function: updateQuery],
        arithmeticQuery: [Function: arithmeticQuery],
        nameIndexes: [Function: nameIndexes],
        addIndexQuery: [Function: addIndexQuery],
        addConstraintQuery: [Function: addConstraintQuery],
        getConstraintSnippet: [Function: getConstraintSnippet],
        removeConstraintQuery: [Function: removeConstraintQuery],
        quoteTable: [Function: quoteTable],
        quote: [Function: quote],
        quoteIdentifiers: [Function: quoteIdentifiers],
        escape: [Function: escape],
        selectQuery: [Function: selectQuery],
        escapeAttributes: [Function: escapeAttributes],
        generateInclude: [Function: generateInclude],
        generateJoin: [Function: generateJoin],
        generateThroughJoin: [Function: generateThroughJoin],
        _generateSubQueryFilter: [Function: _generateSubQueryFilter],
        _getRequiredClosure: [Function: _getRequiredClosure],
        getQueryOrders: [Function: getQueryOrders],
        selectFromTableFragment: [Function: selectFromTableFragment],
        setAutocommitQuery: [Function: setAutocommitQuery],
        setIsolationLevelQuery: [Function: setIsolationLevelQuery],
        generateTransactionId: [Function: generateTransactionId],
        startTransactionQuery: [Function: startTransactionQuery],
        deferConstraintsQuery: [Function: deferConstraintsQuery],
        setConstraintQuery: [Function: setConstraintQuery],
        setDeferredQuery: [Function: setDeferredQuery],
        setImmediateQuery: [Function: setImmediateQuery],
        commitTransactionQuery: [Function: commitTransactionQuery],
        rollbackTransactionQuery: [Function: rollbackTransactionQuery],
        addLimitAndOffset: [Function: addLimitAndOffset],
        whereQuery: [Function: whereQuery],
        whereItemsQuery: [Function: whereItemsQuery],
        OperatorsAliasMap: false,
        setOperatorsAliases: [Function: setOperatorsAliases],
        whereItemQuery: [Function: whereItemQuery],
        _findField: [Function: _findField],
        _replaceAliases: [Function: _replaceAliases],
        _whereGroupBind: [Function: _whereGroupBind],
        _whereBind: [Function: _whereBind],
        _whereJSON: [Function: _whereJSON],
        _traverseJSON: [Function: _traverseJSON],
        _castKey: [Function: _castKey],
        _getJsonCast: [Function: _getJsonCast],
        _joinKeyValue: [Function: _joinKeyValue],
        _getSafeKey: [Function: _getSafeKey],
        _prefixKey: [Function: _prefixKey],
        _whereParseSingleValueObject: [Function: _whereParseSingleValueObject],
        getWhereConditions: [Function: getWhereConditions],
        parseConditionObject: [Function: parseConditionObject],
        isIdentifierQuoted: [Function: isIdentifierQuoted],
        booleanValue: [Function: booleanValue],
        _dialect: [Circular],
        sequelize: [Circular],
        typeValidation: undefined } },
  queryInterface:
   QueryInterface {
     sequelize: [Circular],
     QueryGenerator:
      { dialect: 'mysql',
        OperatorMap: [Object],
        createSchema: [Function: createSchema],
        showSchemasQuery: [Function: showSchemasQuery],
        versionQuery: [Function: versionQuery],
        createTableQuery: [Function: createTableQuery],
        showTablesQuery: [Function: showTablesQuery],
        addColumnQuery: [Function: addColumnQuery],
        removeColumnQuery: [Function: removeColumnQuery],
        changeColumnQuery: [Function: changeColumnQuery],
        renameColumnQuery: [Function: renameColumnQuery],
        handleSequelizeMethod: [Function: handleSequelizeMethod],
        _toJSONValue: [Function: _toJSONValue],
        upsertQuery: [Function: upsertQuery],
        deleteQuery: [Function: deleteQuery],
        showIndexesQuery: [Function: showIndexesQuery],
        showConstraintsQuery: [Function: showConstraintsQuery],
        removeIndexQuery: [Function: removeIndexQuery],
        attributeToSQL: [Function: attributeToSQL],
        attributesToSQL: [Function: attributesToSQL],
        quoteIdentifier: [Function: quoteIdentifier],
        _checkValidJsonStatement: [Function: _checkValidJsonStatement],
        jsonPathExtractionQuery: [Function: jsonPathExtractionQuery],
        _getForeignKeysQueryFields: [Function: _getForeignKeysQueryFields],
        getForeignKeysQuery: [Function: getForeignKeysQuery],
        getForeignKeyQuery: [Function: getForeignKeyQuery],
        dropForeignKeyQuery: [Function: dropForeignKeyQuery],
        _templateSettings: [Object],
        options: [Object],
        extractTableDetails: [Function: extractTableDetails],
        addSchema: [Function: addSchema],
        dropSchema: [Function: dropSchema],
        describeTableQuery: [Function: describeTableQuery],
        dropTableQuery: [Function: dropTableQuery],
        renameTableQuery: [Function: renameTableQuery],
        insertQuery: [Function: insertQuery],
        bulkInsertQuery: [Function: bulkInsertQuery],
        updateQuery: [Function: updateQuery],
        arithmeticQuery: [Function: arithmeticQuery],
        nameIndexes: [Function: nameIndexes],
        addIndexQuery: [Function: addIndexQuery],
        addConstraintQuery: [Function: addConstraintQuery],
        getConstraintSnippet: [Function: getConstraintSnippet],
        removeConstraintQuery: [Function: removeConstraintQuery],
        quoteTable: [Function: quoteTable],
        quote: [Function: quote],
        quoteIdentifiers: [Function: quoteIdentifiers],
        escape: [Function: escape],
        selectQuery: [Function: selectQuery],
        escapeAttributes: [Function: escapeAttributes],
        generateInclude: [Function: generateInclude],
        generateJoin: [Function: generateJoin],
        generateThroughJoin: [Function: generateThroughJoin],
        _generateSubQueryFilter: [Function: _generateSubQueryFilter],
        _getRequiredClosure: [Function: _getRequiredClosure],
        getQueryOrders: [Function: getQueryOrders],
        selectFromTableFragment: [Function: selectFromTableFragment],
        setAutocommitQuery: [Function: setAutocommitQuery],
        setIsolationLevelQuery: [Function: setIsolationLevelQuery],
        generateTransactionId: [Function: generateTransactionId],
        startTransactionQuery: [Function: startTransactionQuery],
        deferConstraintsQuery: [Function: deferConstraintsQuery],
        setConstraintQuery: [Function: setConstraintQuery],
        setDeferredQuery: [Function: setDeferredQuery],
        setImmediateQuery: [Function: setImmediateQuery],
        commitTransactionQuery: [Function: commitTransactionQuery],
        rollbackTransactionQuery: [Function: rollbackTransactionQuery],
        addLimitAndOffset: [Function: addLimitAndOffset],
        whereQuery: [Function: whereQuery],
        whereItemsQuery: [Function: whereItemsQuery],
        OperatorsAliasMap: false,
        setOperatorsAliases: [Function: setOperatorsAliases],
        whereItemQuery: [Function: whereItemQuery],
        _findField: [Function: _findField],
        _replaceAliases: [Function: _replaceAliases],
        _whereGroupBind: [Function: _whereGroupBind],
        _whereBind: [Function: _whereBind],
        _whereJSON: [Function: _whereJSON],
        _traverseJSON: [Function: _traverseJSON],
        _castKey: [Function: _castKey],
        _getJsonCast: [Function: _getJsonCast],
        _joinKeyValue: [Function: _joinKeyValue],
        _getSafeKey: [Function: _getSafeKey],
        _prefixKey: [Function: _prefixKey],
        _whereParseSingleValueObject: [Function: _whereParseSingleValueObject],
        getWhereConditions: [Function: getWhereConditions],
        parseConditionObject: [Function: parseConditionObject],
        isIdentifierQuoted: [Function: isIdentifierQuoted],
        booleanValue: [Function: booleanValue],
        _dialect: [Object],
        sequelize: [Circular],
        typeValidation: undefined } },
  models: {},
  modelManager: ModelManager { models: [], sequelize: [Circular] },
  connectionManager:
   ConnectionManager {
     sequelize: [Circular],
     config:
      { database: 'node',
        username: 'root',
        password: '1234567890',
        host: 'localhost',
        port: undefined,
        pool: [Object],
        protocol: 'tcp',
        native: false,
        ssl: undefined,
        replication: false,
        dialectModulePath: null,
        keepDefaultTimezone: undefined,
        dialectOptions: undefined },
     dialect:
      MysqlDialect {
        sequelize: [Circular],
        connectionManager: [Circular],
        QueryGenerator: [Object] },
     versionPromise: null,
     dialectName: 'mysql',
     pool:
      Pool {
        domain: null,
        _events: {},
        _eventsCount: 0,
        _maxListeners: undefined,
        _config: [Object],
        _Promise: [Object],
        _factory: [Object],
        _draining: false,
        _started: false,
        _waitingClientsQueue: [Object],
        _factoryCreateOperations: Set {},
        _factoryDestroyOperations: Set {},
        _availableObjects: [Object],
        _testOnBorrowResources: Set {},
        _testOnReturnResources: Set {},
        _validationOperations: Set {},
        _allObjects: Set {},
        _resourceLoans: Map {},
        _evictionIterator: [Object],
        _evictor: DefaultEvictor {},
        _scheduledEviction: null },
     lib:
      { createConnection: [Function],
        connect: [Function],
        Connection: [Function: Connection],
        createPool: [Function],
        createPoolCluster: [Function],
        createQuery: [Function: createQuery],
        Pool: [Function: Pool],
        createServer: [Function],
        PoolConnection: [Object],
        escape: [Function: escape],
        escapeId: [Function: escapeId],
        format: [Function: format],
        raw: [Function: raw],
        createConnectionPromise: [Getter],
        createPoolPromise: [Getter],
        createPoolClusterPromise: [Getter],
        Types: [Getter],
        Charsets: [Getter],
        CharsetToEncoding: [Getter],
        setMaxParserCache: [Function],
        clearParserCache: [Function] } },
  importCache: {},
  test:
   { _trackRunningQueries: false,
     _runningQueries: 0,
     trackRunningQueries: [Function: trackRunningQueries],
     verifyNoRunningQueries: [Function: verifyNoRunningQueries] } }

模型 product.js

const Sequelize = require('sequelize');

const sequelize = require('./dbconfig');


const Product = sequelize.define('product', {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true
  },
  title: Sequelize.STRING,
  price: {
    type: Sequelize.DOUBLE,
    allowNull: false
  },
  imageUrl: {
    type: Sequelize.STRING,
    allowNull: false
  },
  description: {
    type: Sequelize.STRING,
    allowNull: false
  }
});

module.exports = Product;

App.js

const express = require('express');
const feedroutes = require('./routes/feed');
const bodyParser = require('body-parser');
const sequelize = require('./dbconfig');


const app = express()

app.use(bodyParser.json());//application/json

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    next();
});

app.use('/feed',feedroutes);

sequelize.sync().then(reslut => {
    console.log(reslut);
    app.listen(8080); 

})
.catch(error => {
    console.log(error);   
});

dbconfig.js

const Sequelize = require('sequelize');

const sequelize = new Sequelize('node','root','1234567890', { 
    operatorsAliases: false ,
    dialect: 'mysql',
    host:'localhost'

});


module.exports = sequelize;

2 个答案:

答案 0 :(得分:1)

由于您的product模型位于单独的文件中,因此需要使用sequelize实例上可用的import方法将其导入,如下所示

模型 product.js

module.exports = function(sequelize, Sequelize) {
    const Product = sequelize.define('product', {
        id: {
            type: Sequelize.INTEGER,
            autoIncrement: true,
            allowNull: false,
            primaryKey: true
        },
        title: Sequelize.STRING,
        price: {
            type: Sequelize.DOUBLE,
            allowNull: false
        },
        imageUrl: {
            type: Sequelize.STRING,
            allowNull: false
        },
        description: {
            type: Sequelize.STRING,
            allowNull: false
        }
    });

    module.exports = Product;
};

dbconfig.js

const Sequelize = require('sequelize');

const sequelize = new Sequelize('node','root','1234567890', { 
    operatorsAliases: false ,
    dialect: 'mysql',
    host:'localhost'

});

sequelize.import('path/to/product/model');

module.exports = sequelize;

引用sequelize import

项目Demo

答案 1 :(得分:0)

您的route middleware始终应位于sequelize.sync()之后(不仅sequelize.sync(),而且应与应用程序相关的所有配置)

在使用res.render()res.send()等进行路由响应之后,将不会调用next()

您可以在路由中间件之后找到error handling middleware