在vuejs中导入sequelize模型

时间:2018-04-25 18:43:24

标签: vue.js electron sequelize.js

我正在使用电子+ vuejs + sequelize建立一个CRUD应用程序,我使用 sequelize init 并配置 .sequelizerc ,如下所示

const path = require('path');

module.exports = {
  'config': path.resolve('src/renderer/database/config', 'config.json'),
  'models-path': path.resolve('src/renderer/database', 'models'),
  'seeders-path': path.resolve('src/renderer/database', 'seeders'),
  'migrations-path': path.resolve('src/renderer/database', 'migrations')
}

现在我试图用数据库中的数据填充表格,我试图以多种方式导入模型,总是导致错误。

错误:未捕获TypeError:Path必须是字符串。收到未定义的

组件:

var models = require('./../../database/models'); // LINE WITH ERROR

export default {
  name: "user-index",
  data: function() {
    return {
      users: []
    };
  },
  created: function() {
    models.Users.findAll().then(users => {
      //
    });
  },
  components: {},
  methods: {}
};

感谢。

修改

我发现了问题,它在models / index.js中:

'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(__filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(__dirname + '/../config/config.json')[env];
var db        = {};

if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    var model = sequelize['import'](path.join(__dirname, file)); // THIS LINE
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

1 个答案:

答案 0 :(得分:1)

我修改后将path.join更改为path.resolve并更改此内容:

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

for (var modelName in db) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
}

在models / index.js文件中。