Explain the method of sharing database connection between Node.js modules _ basics

Source: Internet
Author: User
Tags mongodb

The title itself is a proposition, because in the case of default, each module in a node.js application is a shared database connection. But if the posture is not right, it can be ugly and may even be wrong.

You can skip the following section and go straight to the point.

Background
recently in the professional curriculum design, the title is "Ticket booking management system." The demand is simpler, try to take the node.js of the recent study to do. Originally still in the research with what node.js framework is more appropriate, looked at a few frames found this is overkill, have to look at the documents to check the time is not as direct to write. Finally, I will put the code on the Github, welcome everyone to criticize correct.

Database, think I am more familiar with and like JSON (SQL did not learn to admit Bai-_-#), so chose the MongoDB. Node + Mongo is an increasingly popular back-end combination in recent years, with lots of information on how to use it together online. But in order to save time (course design is one weeks), focus on the system and logic, I used mongoose this is dedicated to MongoDB data modeling node.js extension, use it to greatly reduce the operation of the database code.

Business
I built two data models (model), one for users (user) and one for Flight (Flight), encapsulated in User.js, flight.js two modules (module). Model is responsible for and database interaction, users and flights of these two modules need to connect the database, at the beginning of my code is this:

-----user.js-----
//Require mongoose.js reference mongoose.js
var M = require (' Mongoose ');
Connect to Database
m.connect (' mongodb://localhost/test ');
... some other code ...

-----flight.js-----
//Require mongoose.js reference 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 ');

And not to say that this kind of writing is not DRY, this way itself is wrong. When I run Index.js, the following error occurs.

> Node index.js
> Connection error: {[error:trying to open unclosed Connection.] State:2}

The error is: Attempt to open a connection that is not closed.

So we should connect the database in one place and then other modules that need to connect to the database to interact with the database through this module. As if strip, no hesitation to roar: "On the wall is an outlet, you do not rob!" Come on, let me! You guys... You can do it! ”

Specific programmes
we put the action of connecting the database into a module and expose the connection to the other modules in the application, and then other modules that need to connect to the database refer to the connection.

-----database.js-----
var M = require (' Mongoose ');
M.connect (' mongodb://localhost/test ');
Reference to the database connection create a reference for this connection to
var db = m.connection;
Expose to modules that require database.js exposes this reference to other modules referencing the database module
module.exports = DB;

-----user.js-----flight.js Similar to-----
//... some other code ...
We'll pass the reference to the database connection as a parameter in models.js
module.exports = function (db) {
  if db) {
    //... do things with the "C" Onnection ... If you are connected to a database, you can perform database-related operations
  }

//-----models.js-----
//Require database module, retrieve the The reference to database connection references the DATABSE module, obtaining a reference to the DB connection
var db = require ('./database ');
The database connection to the reference to the need to connect the database module, the task is completed!
var user = require ('./user ') (db),
  flight = require ('./flight ') (db);

This is a way to have multiple modules of a node.js application share a database connection. I saw it on the StackOverflow. If you have a better way, welcome to share in the comments!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.