this is my files sturcture:
-models
-user.js
-room.js
-database.js
-controllers
-createRoom.js
-routes.js
..
user.js and room.js are modules i want to import in database.js. right now im doing like this:
in database.js:
var mysql = require('mysql');
var Sequelize = require('sequelize');
var db = new Sequelize('test', 'root', 'root', {
dialect: "mysql",
port: 3306
})
var User = require('./user.js')(Sequelize, db);
var Room = require('./room.js')(Sequelize, db);
module.exports = function(){
//code...
};
in user.js/room.js
module.exports = function (Sequelize, db) {
var Room = db.define('Room', {
room_id : {type: Sequelize.INTEGER, allowNull: false, autoIncrement: true, primaryKey: true},
})
db
.sync({force: true})
.complete(function (err) {})
so far so good, but when i need to import user.js or room.js in other files besides database.js(eg, createRoom.js), i have trouble importing them because theres no Sequelize and db defined like in the database.js. does it mean i have to connect to the database and require Sequelize again whenever i need to use user.js and room.js module in other files? is there a better way to work around this?? thanks!
you have different possibilities here
re-export models:
in your database.js
//init code as seen
module.exports.Room = Room
importing somewhere else
require('../models/database').Room
make your database.js dependency
in database.js
module.export = { Sequelize: Sequelize, db : db}
in room.js
var dbModule = require('./database')
module.exports = dbModule.Sequelize.define('Room', /*....*/)
Attach the model to the init function
in room.js
module.exports = roomInit
function roomInit(Sequelize, db) {
roomInit.Room = db.define('Room', {
room_id : {type: Sequelize.INTEGER, allowNull: false, autoIncrement: true, primaryKey: true}
})
db
.sync({force: true})
.complete(function (err) {})
}
usage
require('./room').Room
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments