I'm following a tutorial which uses sequelize with an express project. Here's the user.js model:
// in models/User.js
module.exports = function(sequelize, DataTypes) {
return sequelize.define('User', {
first_name: DataTypes.STRING,
last_name: DataTypes.STRING,
}, {
instanceMethods: {
countTasks: function() {
// how to implement this method ?
}
}
});
};
Then he uses User in various of ways, for example:
var user = User.build({ first_name: 'John', last_name: 'Doe' });
I understand the code in general, but I don't understand completely why module.exports gets a function with two parameters (sequelize, DataTypes). I haven't seen it initialized anywhere in the code. How is it working then?
If you are following this guide you will see in models/index.js that all model definitions are looped through and passed to seqelize.import().
You will find that this line of code within sequelize.import calls the model's module function and passes a reference to sequelize and DataTypes to the model.
In the tutorial you referenced, the author uses a similar method within models/index.js
Since the link does not work and I could not find it on their current site, I copied the code from their site using The Wayback Machine. I also updated the second link to point to the 2.0 docs instead of master.
models/index.js
"use strict";
var fs = require("fs");
var path = require("path");
var Sequelize = require("sequelize");
var env = process.env.NODE_ENV || "development";
var config = require(__dirname + '/../config/config.json')[env];
var sequelize = new Sequelize(config.database, config.username, config.password, config);
var db = {};
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf(".") !== 0) && (file !== "index.js");
})
.forEach(function(file) {
var model = sequelize["import"](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if ("associate" in db[modelName]) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;