Skip to content

Instantly share code, notes, and snippets.

@edhaase
Last active December 10, 2021 05:38
Show Gist options
  • Save edhaase/fb54f2356f3d7a8f182f to your computer and use it in GitHub Desktop.
Save edhaase/fb54f2356f3d7a8f182f to your computer and use it in GitHub Desktop.
Load sequelize models from a folder
/*
* Not actually a JS file; Normally you'd break these components up.
*/
/* creating the database connection */
var db = new Sequelize('database', 'username', 'password', ...);
/* loading the models */
var fs = require('fs');
var path = require('path');
var models = {};
fs.readdirSync('model/').forEach(function(filename) {
var model = {};
model.path = path.join(__dirname, 'model/', filename)
model.name = filename.replace(/\.[^/.]+$/, "");
model.resource = db.import(model.path);
// model.service = epilogue.resource({model: model.resource});
models[model.name] = model;
});
/* Student.js - Example of a complex model */
var path = require('path');
module.exports = function(sequelize, DataTypes) {
// Define resource
var Student = sequelize.define('Student', {
firstname: DataTypes.STRING,
lastname: DataTypes.STRING,
name: { type: DataTypes.STRING }
},
// Other properties
{
indexes: [{fields: ['firstname', 'lastname']}]
});
var Course = sequelize.import(path.join(__dirname, 'course'));
Student.hasMany(Course);
return Student;
}
@foocode
Copy link

foocode commented Aug 26, 2020

in my line code error model.resource = db.import(model.path);
what's wrong with my line of code?

.import() was removed in sequelize 6.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment