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;
}
@RianKhanafi
Copy link

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

lines code
var models = {};
fs.readdirSync(__dirname + "/generated")
.filter((filename) => filename !== "index.js")
.forEach(function (filename) {
let model = {};
model.path = path.join(__dirname, "/generated", filename);
model.name = filename.replace(/.[^/.]+$/, "");
model.resource = db.import(model.path);
models[model.name] = model;
// console.log(model);
});

error message:

D:\MyProject\dashboard-backend\src\graphql\models\database.js:44
model.resource = db.import(model.path);
^

TypeError: db.import is not a function
at forEach (D:\MyProject\dashboard-backend\src\graphql\models/database.js:36:22)
at Array.forEach ()
at Object. (D:\MyProject\dashboard-backend\src\graphql\models/database.js:32:4)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Module._compile (D:\MyProject\dashboard-backend\node_modules\pirates\lib\index.js:99:24)
at Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Object.newLoader [as .js] (D:\MyProject\dashboard-backend\node_modules\pirates\lib\index.js:104:7)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)

@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