Home > Web Front-end > JS Tutorial > Detailed explanation of the method of sharing database connections between Node.js modules (graphic tutorial)

Detailed explanation of the method of sharing database connections between Node.js modules (graphic tutorial)

亚连
Release: 2018-05-21 11:25:03
Original
1861 people have browsed it

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');
Copy after login

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 }
Copy after login

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 );
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template