Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sequelize is not defined - Sequelize and consign

I'm new in node.

I'm trying to add Sequelize in my simple application with cosign.

config/db.js

var Sequelize = require('sequelize');

var sequelize = new Sequelize('test', 'root', '', {

host: 'localhost',
dialect: 'mysql',

 pool: {
max: 5,
min: 0,
idle: 10000
}

});

module.exports = function () {
return sequelize
}

model/user.js

var Sequelize = require('sequelize');

module.exports = function(application, req, res){

var User = sequelize.define('user', {
username: {
type: Sequelize.STRING,
}
}, {
freezeTableName: true // Model tableName will be the same as the model name
});

User.create({ username: 'fnord'})
.then(function() {
console.log('criado!');
})
}

config/server.js

...
consign()
.include('app/routes')
.then('config/db.js')
.then('app/models')
.then('app/controllers')
.into(app);

module.exports = app;

I'm getting the error sequelize is not defined´ onvar User = sequelize.define('user', {`

What I'm doing wrong?

like image 810
Igor Martins Avatar asked May 10 '26 19:05

Igor Martins


1 Answers

Create an index.js file inside your moldes folder like this:

"use strict";

var fs        = require("fs");
var path      = require("path");
var Sequelize = require("sequelize");

var sequelize = new Sequelize(global.config.dbConfig.name, global.config.dbConfig.user, global.config.dbConfig.password, {
  host: global.config.dbConfig.host,
  port: global.config.dbConfig.port,
  pool: false
});

var db = {};

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

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

db.sequelize = sequelize;

module.exports = db;

and in your user.js do something like this:

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define("User", {
    username: {
      type: DataTypes.STRING
    }, 
    {
      freezeTableName: true // Model tableName will be the same as the model name 
    }
  });

  return User;
}

http://docs.sequelizejs.com/en/1.7.0/articles/express/

like image 175
Ricardo Machado Avatar answered May 12 '26 08:05

Ricardo Machado