Sequelize: Demand Against Import

In the documentation for sequlize, they use the import function like this:

// in your server file - eg app.js var 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 = function(sequelize, DataTypes) { return sequelize.define("Project", { name: DataTypes.STRING, description: DataTypes.TEXT }) } 

However, what would be so wrong with this?

 // in your server file - eg app.js var Project = require(__dirname + "/path/to/models/project") // The model definition is done in /path/to/models/project.js var Project = sequelize.define("Project", { name: Sequelize.STRING, description: Sequelize.TEXT }); module.exports = Project 
+6
source share
1 answer

Well, as you can see, two things are needed to determine your model:

  • Sequelize or DataTypes
  • sequelize

In the first example, when using sequelize.import('something'); it is like using require('something')(this, Sequelize); (this is an instance of sequelize)

Both are necessary to initialize your model, but it is important to understand: one of them is classtype, therefore it is global, the other is an instance and must be created with your connection parameters.

So if you do this:

  var Project = sequelize.define("Project", { name: Sequelize.STRING, description: Sequelize.TEXT }); module.exports = Project 

Where did sexualization come from? It must be created and transmitted in some way.

Here is an example with a requirement, not an import:

 // /path/to/app.js var Sequelize = require('sequelize'); var sequelize = new Sequelize(/* ... */); var Project = require('/path/to/models/project')(sequelize, Sequelize); // /path/to/models/project.js module.exports = function (sequelize, DataTypes) { sequelize.define("Project", { name: DataTypes.STRING, description: DataTypes.TEXT }); }; module.exports = Project 

You can even change it so you don’t have to pass Sequelize, requiring it in the model itself, but you still need to create a sequelize instance before defining the model.

+7
source

Source: https://habr.com/ru/post/976889/


All Articles