如何在Nodejs中实现控制器中的模型?

时间:2017-03-24 03:22:12

标签: javascript node.js express model-view-controller

我试图通过sequelize module在节点中使用模型对象。

我有类似的东西:

File structure:
models
  index.js
  user.js
controllers
  userController.js
routes
  route.js

==========================

models/users.js
//generated through sequelize cli
'use strict';
module.exports = function(sequelize, DataTypes) {
  var user = sequelize.define('user', {
    name: DataTypes.STRING,
    job: DataTypes.STRING
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
      }
    }
  });
  return user;
};

models/index.js //通过sequelize生成文件。

controllers/userController.js

var model = require('../models/user');

var userController = function(){
    function createOne (req, res) {
         model.create({
             'name': 'John',
             'job':'manager'
         }).then(function(test){
             console.log(test);
         })
    }

    return {
        createOne: createOne        
    }
}

module.exports = userController;

当我的路线请求userController.createOne()时,我收到model.create is not a function

我不确定问题是什么,以及如何将模型注入控制器。任何人都可以帮我吗?非常感谢!

更新

my models/index.js //generated by sequelize cli

'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(module.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]);
} else {
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

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

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

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

module.exports = db;

1 个答案:

答案 0 :(得分:1)

通常你单独定义模型,然后让ngAfterViewInit将这些正确地分阶段进入Sequelize对象。后:

models/index.js

然后你可以拨打const models = require('../models'); const User = models.User; 等等。裸模型定义文件不是一个完整的包。