


Detailed explanation of the method of sharing database connections between Node.js modules (graphic tutorial)
We can write a unified database connection module for sharing between modules in the local Node environment. Next, we will explain in detail the method of sharing database connections between Node.js modules.
This title itself is a Proposition, because by default, each module in a Node.js application shares the same database connection. But if the posture is wrong, it can look ugly or even go wrong.
You can ignore the following part and get to the point directly.
BackgroundRecently I am designing a professional course, the title is "Ticket Reservation Management System". The requirement is relatively simple, so I tried to use Node.js, which I have been learning recently, to do it. I was originally investigating which Node.js framework would be more suitable. After looking at a few frameworks, I realized that this was a big overkill. If I didn’t have time to look up documents and information, I might as well start writing it directly. After I finish writing the code, I will put it on Github. Everyone is welcome to criticize and correct me.
In terms of database, I thought I was more familiar with and liked JSON (just admit it if you haven’t learned SQL well-_-#), so I chose MongoDB. Node Mongo is an increasingly popular backend combination in recent years, and there is a lot of information on the Internet about how to use it together. But in order to save time (the course design only takes more than a week) and focus more on the system and logic, I used Mongoose, a Node.js extension specifically used for MongoDB data modeling, to greatly reduce the time required to operate the database. code.
The main topicI established two data models (Model), one is the user (User) and the other is the flight (Flight), which are encapsulated into user.js and flight.js respectively. Inside a module. Model is specifically responsible for interacting with the database. Both the user and flight modules need to connect to the database. At the beginning, my code was like this:
// ----- user.js ----- // require mongoose.js 引用mongoose.js var M = require('mongoose'); // connect to database 连接数据库 M.connect('mongodb://localhost/test'); // ... some other code ... // ----- flight.js ----- // require mongoose.js 引用mongoose.js var M = require('mongoose'); // connect to database 连接数据库 M.connect('mongodb://localhost/test'); // ... some other code ... // ----- models.js ----- var user = require('./user'), flight = require('./flight'); // ----- index.js ----- var Models = require('./models');
Not to mention that this way of writing is not DRY at all, this method itself Just wrong. When I run index.js, I get the following error.
> node index.js > Connection error: { [Error: Trying to open unclosed connection.] state: 2 }
The error is: An attempt was made to open a connection that was not closed.
So we should connect to the database once in one place, and then other modules that need to connect to the database interact with the database through this module. It's like a power strip, shouting without hesitation: "There is only one socket on the wall, don't grab it! Let me do it! You... That's it!"
Specific PlanWe put the action of connecting to the database into a module, and expose the connection to other modules in the entire application, and then other modules that need to connect to the database can reference this connection.
// ----- database.js ----- var M = require('mongoose'); M.connect('mongodb://localhost/test'); // reference to the database connection 为这个连接创建一个引用 var db = M.connection; // expose to modules that require database.js 把这个引用暴露给引用 database 模块的其他模块 module.exports = db; // ----- user.js ----- flight.js 类似 ----- // ... some other code ... // 我们会在 models.js 中,把数据库连接的引用作为参数传进来 module.exports = function( db ){ if( db ){ // ... do things with the connection ... 如果连接了数据库,就可以执行数据库相关的操作了 } } // ----- models.js ----- // require database module, retrieve the reference to database connection 引用 databse 模块,获取数据库连接的引用 var db = require('./database'); // 把数据库连接的引用传入需要连接数据库的模块,任务完成! var user = require('./user')( db ), flight = require('./flight')( db );
This is a way to let multiple modules of a Node.js application share a database connection. I saw this on StackOverflow.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Detailed explanation of several borrowing methods in JavaScript (picture and text tutorial)
Implemented using JavaScript String method of pattern matching
javascript This is explained in detail (graphic tutorial)
The above is the detailed content of Detailed explanation of the method of sharing database connections between Node.js modules (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
