NodeJs如何使用Sequelize?

时间:2019-03-24 15:49:45

标签: node.js sequelize.js

我是Node的新手,我正在尝试学习Sequelize,
由于它很容易与Hibernate等ORM一起使用,
我正在使用MySql来实现要使用的示例,
但是,我面临着一个简单实现的问题,
我使用以下命令安装了该库-

1. npm install --save sequelize
2. npm install --save mysql2

我有两个文件-
1. app.js(主代码)
2. code.js(模型类)

1。 app.js-

const Sequelize = require('sequelize');

const code = require('./code');

const sequelize = new Sequelize('junit', 'root', 'root', {
  host: 'localhost',
  dialect: 'mysql'/* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */,
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
});

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

  code.findAll().then(codes => {
    console.log("All users:", JSON.stringify(codes, null, 4));
  })
  .catch(err => console.log(err));

2。 code.js-

const Sequelize = require('sequelize');


module.exports = (sequelize) => {
class Code extends Model {}
  Code.init({
    id: {
        type: Sequelize.INTEGER
      },
      name: {
        type: Sequelize.STRING
      },
      createdBy: {
        type: Sequelize.INTEGER
      }
  }, {
    sequelize,
    // options
  });
}

但是在运行我的app.js文件时出现以下错误-

/home/user/office/pocs/test/app.js:26
  code.findAll().then(codes => {
       ^

TypeError: code.findAll is not a function
    at Object.<anonymous> (/home/user/office/pocs/test/app.js:26:8)
    at Module._compile (internal/modules/cjs/loader.js:734:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:745:10)
    at Module.load (internal/modules/cjs/loader.js:626:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:566:12)
    at Function.Module._load (internal/modules/cjs/loader.js:558:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:797:12)
    at executeUserCode (internal/bootstrap/node.js:526:15)
    at startMainThreadExecution (internal/bootstrap/node.js:439:3)

我要引用此文档-
http://docs.sequelizejs.com/manual/getting-started
但这些示例未包含完整的代码,导入等
所以有点难以理解,
有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

您需要进行一些更改:

首先,您需要在函数内部返回Code类。

const Sequelize = require('sequelize');

module.exports = (sequelize) => {
  class Code extends Sequelize.Model {}
  Code.init({
    ...
  }, {
    sequelize,
    // options
  });
  return Code;
}

第二,您正在导出./code内部的函数。您必须使用创建的sequelize对象来调用此功能:

const sequelize = new Sequelize('junit', 'root', 'root', {
  ...
});

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

最后,我建议您保持大小写约定,并在导入过程中在标题栏中引用Code模型,例如const Code = require('./code')(sequelize);