Nodejs with Sequelizejs using separate files per model

This is an awkward start-up question, but I just want to solve my problems with Sequelages. I want to split each model into my own file to save the source. To do this, I need require("sequelize') and var sequelize = new Sequelize('DB-Name', 'DB-User', 'DB-Password'); at the beginning of each file.

My question is: will this create a new database connection for each model, or will it just reuse the same connection? Should I abandon the whole concept of β€œone model for a file” and just create a master Models.js file?

I am very new to Node and am still used to its conventions. Thanks for the help!

+11
source share
2 answers

Each model is defined as its own module, which you export:

 module.exports = function(sequelize, DataTypes){ return sequelize.define('Brand', { name: { type: DataTypes.STRING, unique: true, allowNull: false }, description: { type: DataTypes.TEXT, allowNull: false }, status: { type: DataTypes.INTEGER, unique: false, allowNull: true } }) }; 

Then just import the module when initializing Sequelize (and you can import many models here):

 var Sequelize = require("sequelize"); var config = require("../../config/config.js"); var sequelize = new Sequelize(config.database, config.username, config.password, { dialect: config.dialect, host: config.host, port: config.port, omitNull: true, logging: false }); var Brand = require("./Brand").Brand; 

You can read more about modules at http://nodejs.org/api/modules.htm , but the above example should get started.

+14
source

In case anyone wants to use the EcmaScript 6 approach, there is a great example with an explanation in the Sequelize documentation here .

 // in your server file - eg app.js const Project = sequelize.import(__dirname + "/path/to/models/project") // The model definition is done in /path/to/models/project.js // As you might notice, the DataTypes are the very same as explained above module.exports = (sequelize, DataTypes) => { return sequelize.define("project", { name: DataTypes.STRING, description: DataTypes.TEXT }) } 

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

 sequelize.import('project', (sequelize, DataTypes) => { return sequelize.define("project", { name: DataTypes.STRING, description: DataTypes.TEXT }) }) 
+2
source

All Articles