Comments (7)
Here is an example using require
./models/index.js
const dotenv = require('dotenv');
const fs = require('fs');
const path = require('path');
const { Sequelize, DataTypes } = require('sequelize');
const filebasename = path.basename(__filename);
const db = {};
// Get env var from .env
dotenv.config()
const { DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_FORCE_RESTART } = process.env;
const config = {
host: DB_HOST,
dialect: 'mysql',
dialectOptions: {
charset: 'utf8',
}
}
const sequelize = new Sequelize(DB_NAME, DB_USER, DB_PASS, config);
fs
.readdirSync(__dirname)
.filter((file) => {
const returnFile = (file.indexOf('.') !== 0)
&& (file !== filebasename)
&& (file.slice(-3) === '.js');
return returnFile;
})
.forEach((file) => {
const model = require(path.join(__dirname, file))(sequelize, DataTypes)
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
const sequelizeOptions = { logging: console.log, };
// Removes all tables and recreates them (only available if env is not in production)
if (DB_FORCE_RESTART === 'true' && process.env.ENV !== 'production') {
sequelizeOptions.force = true;
}
sequelize.sync(sequelizeOptions)
.catch((err) => {
console.log(err);
process.exit();
});
module.exports = db;
./models/User.js
'use strict';
import cryp from 'crypto';
module.exports = function (sequelize, DataTypes) {
const User = sequelize.define('User', {
email: {
type: DataTypes.STRING(50),
allowNull: false,
unique: true,
validate: {
isEmail: { msg: "Please enter a valid email addresss" }
},
isEmail: true
},
password_hash: { type: DataTypes.STRING(80), allowNull: false },
password: {
type: DataTypes.VIRTUAL,
set: function (val) {
//this.setDataValue('password', val); // Remember to set the data value, otherwise it won't be validated
this.setDataValue('password_hash', cryp.createHash("md5").update(val).digest("hex"));
},
validate: {
isLongEnough: function (val) {
if (val.length < 8) {
throw new Error("Please choose a longer password");
}
}
}
},
role: {
type: DataTypes.INTEGER,
allowNull: false
},
active: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 1
}
}, {
classMethods: {
associate: function (models) {
// User.belongsTo(models.Department, { foreignKey: { allowNull: false } });
// User.belongsTo(models.Position, { foreignKey: { allowNull: false } });
// User.belongsTo(models.Profile, { foreignKey: { allowNull: false } });
// User.hasMany(models.Report, { foreignKey: { allowNull: false } });
// User.hasMany(models.Notification, { foreignKey: { allowNull: false } });
// User.hasMany(models.Response, { foreignKey: { allowNull: false } });
}
},
timestamps: true,
// don't delete database entries but set the newly added attribute deletedAt
// to the current date (when deletion was done). paranoid will only work if
// timestamps are enabled
paranoid: false,
// don't use camelcase for automatically added attributes but underscore style
// so updatedAt will be updated_at
underscored: true
});
return User;
};
.env
DB_HOST=localhost
DB_USER=wilo087
DB_PASS=temp
DB_NAME=database_name
DB_FORCE_RESTART=true #Remove and create tables
Full example on:
https://github.com/wilo087/pethome_raffle_backend/tree/develop
from express-example.
As documentation here https://sequelize.org/master/manual/models-definition.html show that it is deprecated.
The documentation suggests to use require, But i am not sure how to use it.
can you provide a small snippet.
//load all Models from models directory dynamically
fs.readdirSync(__dirname).filter(file => {
return (file.indexOf('.') !== 0) && (file !== path.basename(__filename)) && (file.slice(-3) === '.js');
}).forEach(function (filename) {
database.import(path.join(__dirname, '', filename));
});
const models = database.models;
// Set up data relationships
Object.keys(models).forEach(name => {
if ('associate' in models[name]) {
models[name].associate(models);
}
});
from express-example.
This solution reading files from the filesystem seems so nasty to me.
What about an index in the models folder?
I can make a PR.
from express-example.
Hello everyone, I created a new example from scratch. The new example does not use sequelize.import
anymore.
from express-example.
You can use only index file on the model folder, but, what happens if you have more than 30 models with associations, validations functions, hooks, virtual fields, etc.?
Exactly, your code going to look nasty as f**k.
from express-example.
using require() assumes that the package in question isn't using ES5-6 syntax. require isn't a thing in ES modules. What would I use as an alternative then?
from express-example.
If you're using esm, use import
. Sequelize works with both module systems, but this boilerplate is written in cjs
from express-example.
Related Issues (20)
- I'm receiving a ERROR: sequelize is not defined HOT 2
- How to use the transaction? HOT 1
- Add TypeScript Example HOT 2
- Add examples of associations HOT 1
- nodemon index.js doesn't work
- upsert route HOT 1
- Should the directory structure be updated to adapt to the directory structure of Sequelize CLI?
- Contributing and Maintaining information HOT 2
- dynamic imports do not work for defining models HOT 2
- "node_modules/.bin/sequelize" is not work on windows HOT 2
- Unit test hanging or sequelize doesn't close connection HOT 1
- enable Travis CI / Circle CI
- Why we need to define structure of database TWICE? HOT 8
- how to use DataType from req.body HOT 2
- npm install error HOT 4
- duplicate foreignKey when using sequelize.sync() HOT 3
- What does Model.associate() do in model/index.js ? HOT 4
- Please provide an example using sequelize v5 and TypeScript. HOT 6
- Update this repo HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from express-example.