Import

You can also store your model definitions in a single file using the import method. The returned object is exactly the same as defined in the imported file's function. Since v1:5.0 of Sequelize the import is cached, so you won't run into troubles when calling the import of a file twice or more often.

  1. // in your server file - e.g. app.js
  2. const Project = sequelize.import(__dirname + "/path/to/models/project")
  3. // The model definition is done in /path/to/models/project.js
  4. // As you might notice, the DataTypes are the very same as explained above
  5. module.exports = (sequelize, DataTypes) => {
  6. class Project extends sequelize.Model { }
  7. Project.init({
  8. name: DataTypes.STRING,
  9. description: DataTypes.TEXT
  10. }, { sequelize });
  11. return Project;
  12. }

The import method can also accept a callback as an argument.

  1. sequelize.import('project', (sequelize, DataTypes) => {
  2. class Project extends sequelize.Model {}
  3. Project.init({
  4. name: DataTypes.STRING,
  5. description: DataTypes.TEXT
  6. }, { sequelize })
  7. return Project;
  8. })

This extra capability is useful when, for example, Error: Cannot find module is thrown even though /path/to/models/project seems to be correct. Some frameworks, such as Meteor, overload require, and spit out "surprise" results like :

  1. Error: Cannot find module '/home/you/meteorApp/.meteor/local/build/programs/server/app/path/to/models/project.js'

This is solved by passing in Meteor's version of require. So, while this probably fails …

  1. const AuthorModel = db.import('./path/to/models/project');

… this should succeed …

  1. const AuthorModel = db.import('project', require('./path/to/models/project'));