Reputation: 1350
I am working on installing multiple databases in one server. To start this process, I am assigning one database in the index.js export object such that I will be able to add another DB as I build up the system. Below is the description of the issue.
When I run the server.js file, the .sync function for the database db1 syncs Table1 and Table2 and then begins listening on its port. Its clear the server.js file is receiving the module.exports = db
through the var db = require('./models')
. However in the file models/Table1.js the server throws an error TypeError: Cannot read property 'Table1' of undefined
. I did check the console output for db in the models/Table1.js and it's empty, so its clear module.exports = db
is not being accessed in this model.
Can someone provide a solution to correct this issue?
The partial code for the Table1.js model and other files listed above is below:
models/Table1.js
var db = require('./.')
[...]
var new_instance = db.db1.Table1.build({...})
server.js
var db = `require('./models')`
[...]
db.db1.sync(function(err) {});
models/index.js
var sq = new Sequelize(dbname, user, password, config);
db['db1'] = {
Sequelize: Sequelize,
sequelize: sq,
Table1: sq.import(__dirname + '/...'),
Table2: sq.import(__dirname + '/...')
}
module.exports = db;
Upvotes: 1
Views: 916
Reputation: 7401
The module.exports = db
is being accessed, but you have created a cyclic dependency between models/index.js
and models/Table1.js
due to the fact that in the Table1.js
model you require index.js
file and in the index.js
file you perform sequelize.import()
call which performs require(path)
to include the model definition, so in your case it calls require('./Table1.js')
- there comes the cyclic dependency.
You should consider putting the var new_instance = db.db1.Table1.build({...})
somewhere else in order to avoid this situation. Files with model definitions should be only used to create the Model definitions, try to avoid performing additional operations.
Take a look at this question - How to deal with cyclic dependencies in Node.js to find out how you can deal with this kind of situations.
EDIT
According to your comment let's consider simple example with below structure
- script.js
- models
- index.js
- Table1.js
In script.js
var db = require('./models');
var new_instance = db.db1.Table1.build({...});
It can be done if you would not require the script.js
inside any of the files placed inside models
directory.
Upvotes: 1