问题
I've just started using Node.js ORM Sequelize in my application. So far I've defined database models in the same file and used them in my controller files to do basic operations. Here is how I defined Models:
var sqlize = require("sequelize");
var sq = new sqlize('test', 'root', 'root', {
host: 'localhost',
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 10000
}
});
function services(){
var ser = sq.define('services',{
idservices: {
type: sqlize.INTEGER,
autoIncrement: true,
primaryKey: true
},
title: sqlize.STRING,
des: sqlize.TEXT,
vendor: sqlize.STRING,
rating: sqlize.STRING,
pricing_hr: sqlize.STRING,
pricing_mn: sqlize.STRING,
size: sqlize.STRING,
cpu: sqlize.STRING,
ram: sqlize.STRING,
os: sqlize.STRING,
img_path: sqlize.STRING
});
sq.sync();
return ser;
}
function category(){
var category = sq.define('category',{
id: {
type: sqlize.INTEGER,
autoIncrement: true,
primaryKey: true
},
category: sqlize.STRING,
sid: sqlize.INTEGER
},{
freezeTableName: true,
timestamps: false
});
sq.sync();
return category;
}
function cat(){
var cat = sq.define('cat',{
idcat: {
type: sqlize.INTEGER,
autoIncrement: true,
primaryKey: true
},
cat: sqlize.STRING
},{
freezeTableName: true,
timestamps: false
});
sq.sync();
return cat;
}
exports.services=services;
exports.category=category;
exports.cat=cat;
But there is another way where you define models in seperate files and create an index file where you load your models. I find the official documentaion of Sequelize not enough for me to undersatnd the usage. I know how to create models and index.js file but how to use those models in my code is difficult to find. Can anyone please help me with a very simple example (without relations), that includes the defination of models in seperate files and their usage in other code files.
回答1:
EDIT
I've fixed my problem. Now my models are in seperate files and I'm using them in my code. Here's how I've defined my models file services.js
:
module.exports = function(sequelize, DataTypes) {
return sequelize.define('services',{
idservices: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
title: DataTypes.STRING,
des: DataTypes.TEXT,
vendor: DataTypes.STRING,
rating: DataTypes.STRING,
pricing_hr: DataTypes.STRING,
pricing_mn: DataTypes.STRING,
size: DataTypes.STRING,
cpu: DataTypes.STRING,
ram: DataTypes.STRING,
os: DataTypes.STRING,
img_path: DataTypes.STRING
});
};
Then by using sequelize.import in the index.js
I've imported all my models:
var Sequelize = require('sequelize');
// initialize database connection
var sequelize = new Sequelize('test', 'root', 'root', {
host: 'localhost',
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 10000
}
});
// load models
var models = [
'services',
'serviceCategory',
'category'
];
models.forEach(function(model) {
module.exports[model] = sequelize.import(__dirname + '/' + model);
});
// export connection
module.exports.sequelize = sequelize;
Now I can use these models in any file in my project by requiring index.js
like this:
//*********************************************
//Sequlize models to handle database commands;
var models = require('../models/index.js');
var s = models.services; //Services table handler
var sc = models.serviceCategory; //Service Category table handler
var ca = models.category; //Category table handler
Now if you want to use services model options, you can use the services model object:
s.create({title: "anything"}).then(function(task){
task.save;
});
回答2:
Separating the models in files is a scaling factor. Basically it's almost always better if you do this.
You can take a look at Ghost and their models organization, although they don't use sequelize, but another ORM, called bookshelf.
Let me give you an example how I organize my models :
I have one models/
folder which contains all models :
models/user.js
models/assignment.js
Every model has exported only one initialize function
, the user model it looks like this :
/**
* Initialize User definition
*
* @param sequelize Sequelize Instance
* @returns {UserClass} Returns the Users model
*/
module.exports = function( sequelize ) {
/** Create the schema */
var Model = sequelize.define(
'user',
schemaAttributes,
{
instanceMethods : instanceMethods,
classMethods : classMethods
}
);
/** Adding hooks */
Model.beforeCreate( storePassword );
Model.beforeUpdate( storePassword );
return Model;
};
For assignment.js
looks almost the same, but with no hooks :
/**
* Initialize Assignment definition
*
* @param sequelize Sequelize Instance
* @returns {AssignmentClass} Returns the Assignment model
*/
module.exports = function( sequelize ) {
/** Create the schema */
return sequelize.define(
'assignment',
schemaAttributes,
{
instanceMethods : instanceMethods,
classMethods : classMethods
}
);
};
I load the models one by one in another file
Now I have another module called database.js
which manages the configuration of my models. It looks something like this :
var user = require('./models/user.js');
var assignment = require('./models/assignment.js');
var sequelize = new Sequelize({...});
var dbUser = user( sequelize );
var dbAssignment = assignment( sequelize );
/** Define relationships */
dbUser.hasManu( dbAssignment );
module.exports = {
user : dbUser,
assignment : dbAssignment
};
Using this and not something like require( fs.readDirSync( ... ) )
helps my tooling, since the files are parsed and are not dynamic dependencies.
Hope this helps.
来源:https://stackoverflow.com/questions/34281843/creating-models-using-sequelize-in-seperate-files-and-use-them-in-your-project