gpt4 book ai didi

node.js - 避免 Sequelize 类的多个实例

转载 作者:行者123 更新时间:2023-12-03 22:22:54 25 4
gpt4 key购买 nike

我正在尝试使用 Express 和 Sequelize 构建一个基本的数据库模式。我在单独的文件中定义了所有模型。我有一个文件 (models/index.js),我在其中创建了 Sequelize 类的实例、导入模型并建立模型之间的关系。我还有多个 Controller ,每个 Controller 都需要访问从 models/index.js 导出的模型.

这是导入模型的文件:

// models/index.js

var Sequelize = require('sequelize');
var sequelize = new Sequelize('myApp', 'username', 'password');

var User = sequelize.import('./users');
var Contact = sequelize.import('./contacts');
var Conversation = sequelize.import('./conversations');
var Medium = sequelize.import('./mediums');

User.hasMany(Contact);
Contact.belongsTo(User);

Contact.hasMany(Conversation);
Conversation.belongsTo(Contact);

Medium.hasMany(Conversation);
Conversation.belongsTo(Medium);

module.exports.Sequelize = Sequelize;
module.exports.sequelize = sequelize;

module.exports.User = User;
module.exports.Contact = Contact;
module.exports.Conversation = Conversation;
module.exports.Medium = Medium;

这是需要访问模型的 Controller 之一。
// controllers/users.js

var models = require('../models');

module.exports.addUser = function () {
};

module.exports.getUser = function () {
};

这是另一个需要访问模型的 Controller 。
// controllers/contacts.js

var models = require('../models');

module.exports.addContact = function () {
};

module.exports.getContact = function () {
};

module.exports.getAllContacts = function () {
};

我担心的是两个 Controller 都需要 models/index.js文件。每次 models/index.js文件是必需的,则创建 Sequelize 类的新实例,它建立与数据库的新连接。有没有人有任何建议来避免 Sequelize 类的多个实例?

提前致谢!

最佳答案

模块(文件)缓存在 Node 中:

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

If you want to have a module execute code multiple times, then export a function, and call that function.


https://nodejs.org/api/modules.html#modules_caching
这意味着, models/index.js 上的代码只会运行一次

关于node.js - 避免 Sequelize 类的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31909070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com