Nodejs Mongoose Shared Database connection

Source: Internet
Author: User
Tags sublime text

Many people ask: how do I share mongoose in Nodejs to establish a database connection, and then use this database connection elsewhere in this application?

Many foreign postings have been discussed, but the relative dullness of the country, the popularity of technology and the degree of enthusiasm for technology are also evident.

Anyway .... Back to Topic

The following example shows you how to make a database connection and use it elsewhere in the program.

Example based on Express, follow these steps to generate the directory structure of Express and install the necessary packages

1. NPM install-g Express-generator

2. MD mytest && CD mytest (set up a directory and enter the directory)

3. EXPRESS-E (Generate the directory structure of the Web site,-e means using Ejs as the template, the default template is Jade)

4. NPM install-d (Installation dependencies)

5. NPM Install Mongoose

The reason for this example based on Express is that I want to use the route in Express, that's all.

By the way, what editor do you use to write Nodejs code? I use sublime Text 2, very useful.

In this example, we insert new companies (company collections) and new countries (country collections) into the database and we create a Mongoose database connection and use it everywhere.

We classify the code in folders, first in the MyTest directory to build the Util directory, in the Util directory, the schema directory and the Dal directory, the schema directory for the definition of the Schema,dal directory to hold the final write the database code

After building the directory structure such as:

The Db.js file is then built in the Dal directory, and the connection to the database is established in Db.js, with the following code:

varMongoose=require (' Mongoose '); Console.log (' Creating Global Mongoose Connection ... ');//Build the connection stringvarDburi = ' Mongodb://localhost:27017/mytest ';//Create the database connectionMongoose.connect (Dburi);//CONNECTION EVENTS//When successfully connectedMongoose.connection.on (' Connected ',function() {Console.log (' Mongoose default connection open to ' +Dburi);});//If The connection throws an errorMongoose.connection.on (' Error ',function(Err) {Console.log (' Mongoose default connection error: ' +err);});//When the connection is disconnectedMongoose.connection.on (' Disconnected ',function() {Console.log (' Mongoose default connection disconnected ');});//If The Node process ends, close the Mongoose connectionProcess.on (' SIGINT ',function() {Mongoose.connection.close (function() {Console.log (' Mongoose default connection disconnected through app termination '); Process.exit (0); });}); Module.exports=mongoose;

Note the last sentence, where the Mongoose object is used as the output of this module for use elsewhere.

Let's define the schema and use the db.js here.

Define Company's schema first, with the following code:

var mongoose=require ('.. /dal/db.js '); var Schema=Mongoose. Schema; var companyschema=New  Schema ({    name:string}); Module.exports=mongoose.model (' company ', Companyschema);

Then define the schema for the country, which is the following code:

var mongoose=require ('.. /dal/db.js '); var Schema=Mongoose. Schema; var countryschema=New  Schema ({    name:string}); Module.exports=mongoose.model (' Country ', Countryschema);

Note that the output of the above two modules is the model object.

Now write the code to insert the database.

In the Dal folder, create a new Companydal.js file with the following code:

var Company=require ('.. /schema/company.js '); exports.create=function(data,callback) {    var company=New company ({        Name:data.name    });    Company.save (function(err,company) {        if(!  ERR) {            callback (null,company);        }         Else {callback (err,null);}}    );};

In the Dal folder, create a new Countrydal.js file with the following code:

var Country=require ('.. /schema/country.js '); exports.create=function(data,callback) {    var country=New  country ({        Name:data.name    });    Country.save (function(err,country) {        if(!  ERR) {            callback (null, country);        }         Else {            callback (err,null);        }    ) ;};

Okay, now it's time to test the insertion data, for convenience, we define two routes:

A route inserts a piece of data into the company collection when Get/company

A route inserts a piece of data into the country collection when Get/country

Under the routes directory, create a new Company.js file with the following code:

var express = require (' Express '); var router = Express. Router (); var companydal=require ('.. /util/dal/companydal '); Router.get (function(req, res) {  companydal.create ({"name": "My Company"},function(err,result) {      if(!  ERR) {          res.send (json.stringify (Result));      }       Else {          res.send (err);      }   = Router;

Under the routes directory, create a new Country.js file with the following code:

var express = require (' Express '); var router = Express. Router (); var countrydal=require ('.. /util/dal/countrydal '); Router.get (function(req, res) {  countrydal.create ({"name": "My Country"},function(err,result) {      if(!  ERR) {          res.send (json.stringify (Result));      }       Else {          res.send (err);      }   = Router;

Then go back to the App.js file to add these two routes:

var routes = require ('./routes/index '); var users = require ('./routes/users '); var company=require ('./routes/company '); var country=require ('./routes/country '); ... app.use ('/', Routes). ................ ); App.use ('/users ', users); App.use ('/company ', company); App.use ('/country ', country);

The final file directory structure is as follows:

Now let's test it out:

In the command line, enter: Node bin/www, you can see

The message is from Db.js, which indicates that the database has been successfully connected (please crossing remember to start the database with Mongod first)

Accessing Http://http://localhost:3000/company in a browser

Accessing Http://localhost:3000/country in a browser

You can see the following output:

Indicates that the data was inserted successfully.

Here's a summary:

1. From code and results, when inserting data into company and country datasets, the Mongoose object is defined in the db.js used

2. Db.js is executed when node Bin/www launches the application, why is it executed?

Because routes are defined in App.js and are used as middleware

var company=require ('./routes/company '); var country=require ('./routes/country '), .... App.use ('/company ', company), etc....... ; App.use ('/country ', country);

The code for the data access layer is then referenced in the routing file (Routes/company.js, ROUTES/COUNTRY.SJ)

var companydal=require ('.. /util/dal/companydal '); var countrydal=require ('.. /util/dal/countrydal ');

The code for the schema is also referenced in Companydal.js and Countrydal

var Company=require ('.. /schema/company.js '); var Country=require ('.. /schema/country.js ');

Db.js is referenced in the schema code.

var mongoose=require ('.. /dal/db.js ');

So Db.js is called when the program is started, anddb.js no matter how many times it is referenced, it is only called once, which is determined by the require mechanism.

Therefore, the principle of implementing the Mongoose Global database connection is that when the program starts, we define the database connection, and open the database connection, and this Mongoose object as the export of the module, the other need to use the database connection, directly require this module can be

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.