2

This is based on my previous question but more simple because I've figured out the issue is because I did something wrong with module.exports. I'm trying to figure out why I get a TypeError whenever I use any function of the model I created in another file. I have this test code:
index.js:

const { Test } = require('./model.js');

(async () => {
  const test = await Test.create({ name: 'test', desc: 'hello world' });

  console.log(test.name);
})();

db-init.js (run manually):

const { Sequelize, DataTypes } = require('sequelize');

const db = new Sequelize({
  dialect: 'sqlite',
  storage: './database.sqlite',
});

require('./model.js')(db, DataTypes);

db.sync({ force: true }).then(async () => {
  console.log('db connected');
}).catch(console.error);

model.js:

module.exports = (db, DataTypes) => {
  return db.define('test', {
    name: DataTypes.STRING,
    desc: DataTypes.TEXT,
  });
}

The code should print "hello world", but instead I get TypeError: Cannot read properties of undefined (reading 'create'). Sorry if this question is poorly worded.

TacoSnack
  • 129
  • 10

1 Answers1

1
const { Test } = require('./model.js');

and

require('./model.js')(db, DataTypes);

aren't used the same way. The correct one is the registration (function call). In order to use the registered model you need to get it from Sequelize instance:

// here you need to import `db` - Sequelize instance, like created in `db-init.js`
const db = require('./db.js);
const Test = db.models['Test'];

If you don't want to use db-init.js as a module with all registered models along with the Sequelize instance then you need a module that you can import whenever you need to use a registered model:

// db.js
const { Sequelize, DataTypes } = require('sequelize');

const db = new Sequelize({
  dialect: 'sqlite',
  storage: './database.sqlite',
});

require('./model.js')(db, DataTypes);

module.exports = db

I'd recommend to look at my other answer to get an idea how to register models and their associations here

Anatoly
  • 20,799
  • 3
  • 28
  • 42