Jwqq Jwqq -4 years ago 150
Javascript Question

How to instantiate model in controller in Nodejs?

I am trying to use the model object in node through sequelize module.

I have something like these:

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
// generated file through 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;


When my route request
userController.createOne()
, I am getting
model.create is not a function


I am not sure what the issue is and how to get model injected into the controller. Can anyone help me about it? Thanks a lot!

Update:

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;

Answer Source

Normally you define the models individually, then let the models/index.js properly stage these into the Sequelize object. Later:

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

const User = models.User;

Then you can call User.create() and so on. The bare model definition file is not a complete package.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download