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)

May 21, 2018 am 11:25 AM
javascript node.js Interpretation

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to display file suffix under Win11 system? Detailed interpretation How to display file suffix under Win11 system? Detailed interpretation Mar 09, 2024 am 08:24 AM

How to display file suffix under Win11 system? Detailed explanation: In the Windows 11 operating system, the file suffix refers to the dot after the file name and the characters after it, which is used to indicate the type of file. By default, the Windows 11 system hides the suffix of the file, so that you can only see the name of the file in the file explorer but cannot intuitively understand the file type. However, for some users, displaying file suffixes is necessary because it helps them better identify file types and perform related operations.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

In which folder is the cookie data on your computer located? Detailed interpretation In which folder is the cookie data on your computer located? Detailed interpretation Jan 19, 2024 am 10:19 AM

With the continuous development of the Internet, people are increasingly inseparable from browsers. In browsers, everyone will use cookies more or less. However, many people don’t know which folder the cookie data is in. Let’s explain it in detail today. First, we need to understand what cookies are. Simply put, a cookie is a piece of text information stored by the browser, which is used to save some of the user's personal settings in the browser or record the user's historical operations, etc. When the user opens the same website again, c

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles