问题描述
这是一个令人尴尬的初学者问题,但我只是想解决我对 Sequelizejs 的担忧.我想将每个模型拆分成自己的文件,以保持我的源代码组织.为了做到这一点,我需要 require("sequelize')
和 var sequelize = new Sequelize('DB-Name', 'DB-User', 'DB-Password');
在每个文件的开头.
This is an embarrassingly beginner question, but I just want to settle my worries about Sequelizejs. I want to split out each model into its own file to keep my source organized. In order to do that I need to require("sequelize')
and var sequelize = new Sequelize('DB-Name', 'DB-User', 'DB-Password');
at the start of each file.
我的问题是,这会为每个模型创建一个到数据库的新连接,还是会继续重复使用相同的连接?我应该放弃每个文件一个模型"的整个概念而只创建一个主 Models.js 文件吗?
My question is, will that create a new connection to the database per model, or will it just keep re-using the same connection? Should I abandon the whole concept of "one model per file" and just create a master Models.js file?
我对 Node 非常陌生,并且仍在习惯它的约定.感谢您的帮助!
I am very new to Node and am still getting used to its conventions. Thanks for the help!
推荐答案
每个模型都定义为自己的模块,您可以导出该模块:
Every 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 }
})
};
然后在初始化 Sequelize 时简单地导入模块(在这里可以导入很多模型):
Then simply import the module when you initialize 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;
您可以在 http://nodejs.org/api/modules.htm 但上面的例子应该会让你开始.
You can read up more on modules at http://nodejs.org/api/modules.htm but the example above should get you started.
这篇关于带有 Sequelizejs 的 Nodejs,每个模型使用单独的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!