TypeError:UserModel.create不是函数,续集

时间:2018-08-20 23:30:56

标签: node.js sequelize.js

我在使用Sequelize时遇到问题,这是我的代码:

index.js

import {initializeSequelize} from "./config/sequelize_init"

async function main() {
  try {

    let db = await initializeSequelize();

    console.log("DB Connected");

    app.listen(3000, function() {
      console.log("Example app listening on port 3000!");

      const UserModel = require('./api/v1/user/model')

      UserModel.create({fname: "a", lname: "a"});
    });
  } catch (error) {
    console.warn(error);
  }
}

main();

sequelize_init.js

import Sequelize from 'sequelize'

  export async function initializeSequelize() {

    const sequelize = new Sequelize(process.env.MYSQL_NAME, process.env.MYSQL_USER, process.env.MYSQL_PASS, {
        host: process.env.MYSQL_HOST,
        dialect: 'mysql',
        port: process.env.MYSQL_PORT,
        operatorsAliases: false
      });


      const models = {
        User: sequelize.import('../api/v1/user/model.js')
      };

      Object.keys(models).forEach(key => {
        if ('associate' in models[key]) {
          models[key].associate(models);
        }
      });

      models.sequelize = sequelize;
      models.Sequelize = Sequelize;

      let a = await models.sequelize.authenticate();

  }

model.js

module.exports = (sequelize, Sequelize) => {
    return sequelize.define('user', {
          fname: Sequelize.STRING,
          lname: Sequelize.STRING
    });
}

这是我启动服务器时的日志:

Executing (default): SELECT 1+1 AS result (<<<--- I DONT KNOW WHAT IS THIS BTW)
DB Connected
Example app listening on port 3000!

UserModel.create({ fname: "a", lname: "a"});
                        ^

TypeError: UserModel.create is not a function

有人可以帮我吗?

1 个答案:

答案 0 :(得分:-1)

我想您需要模型后才能访问用户模型。