There is often quite a lot of confusion about how best to set up a database connection with Mongoose. So I thought I'd clear it up!

There are two ways of establishing a Mongoose connection, using the default connection or a named connection. In this article we'll be looking at using the default connection.

Let's start with a list of things we want to achieve:

  • Open the connection when the app starts
  • Monitor the connection events
  • Close the connection when the app process terminates
  • Define a schema and build a model that we can use in the app

    Defining the Node.js app

    Let's define a really simple skeleton Node.js app, using the following file structure.

    app.js 
    pages.js 
    model/ 
    - db.js 
    - team.js

    app.js will be the starting point of the application, creating the server and tying everything together. 
    pages.js will contain a rudimentary controller to interact with Mongoose and display output to a browser window 
    model/db.js will hold the database connection and event listeners 
    model/team.js will hold a Mongoose schema definition

    Starting with app.js, we need to require the HTTP module, the db file and the pages file. We'll also create a server that listens to the localhost port of 8888, serving an index page that we will define later in pages.js.

    var http = require('http'),  
    
        db = require('./model/db'),
    
        pages = require('./pages');
    

     

    http.createServer(function (req, res) {  
    
      pages.index(req, res);
    
    }).listen(8888, '127.0.0.1');
    

    Managing the Mongoose connection

    Our model/db.js file is where we'll hold the database connection information and event handlers. We'll also import our schemas & models into here so that the application has access to them. The comments in the code should make it pretty obvious what's going on here.

    // Bring Mongoose into the app 
    
    var mongoose = require( 'mongoose' ); 
    

     

    // Build the connection string 
    
    var dbURI = 'mongodb://localhost/ConnectionTest'; 
    

     

    // Create the database connection 
    
    mongoose.connect(dbURI); 
    

     

    // CONNECTION EVENTS
    
    // When successfully connected
    
    mongoose.connection.on('connected', function () {  
    
      console.log('Mongoose default connection open to ' + dbURI);
    
    }); 
    

     

    // If the connection throws an error
    
    mongoose.connection.on('error',function (err) {  
    
      console.log('Mongoose default connection error: ' + err);
    
    }); 
    

     

    // When the connection is disconnected
    
    mongoose.connection.on('disconnected', function () {  
    
      console.log('Mongoose default connection disconnected'); 
    
    });
    

     

    // If the Node process ends, close the Mongoose connection 
    
    process.on('SIGINT', function() {  
    
      mongoose.connection.close(function () { 
    
        console.log('Mongoose default connection disconnected through app termination'); 
    
        process.exit(0); 
    
      }); 
    
    }); 
    

     

    // BRING IN YOUR SCHEMAS & MODELS // For example 
    
    require('./../model/team');  
    

    Using the Mongoose connection

    Finally, we want to do something with the connection. So in pages.js we want the following code. What we're going to do is require Mongoose, bring the Team model in, create a new team and output it to the browser window.

    var mongoose = require( 'mongoose' ),  
    
        Team = mongoose.model('Team'); 
    

     

    exports.index = function (req, res) {  
    
      Team.create({
    
        Country : "England", 
    
        GroupName: "D", 
    
        CreatedOn: Date.now() 
    
       }, function(err, team) { 
    
    
    							var strOutput; 
    
         res.writeHead(200, { 
    
    
    							'Content-Type': 'text/plain'
         }); 
    
    
    							if (err) { 
    
           console.log(err); 
    
           strOutput = 'Oh dear, we\'ve got an error'; 
    
         } else { 
    
           console.log('Team created: ' + team); 
    
           strOutput = team.Country + ' created in Group ' + team.GroupName + '\nat ' + team.CreatedOn; 
    
         } 
    
         res.write(strOutput); 
    
         res.end(); 
    
       }); 
    
     };
    

    You'd normally want to separate this out into the component parts, the view and the controller, but we want to keep this example streamlined and focused.

    Running the test page

    Run this app by going to the root folder, install Mongoose into the app:

    npm install mongoose  
    

    and run it:

    node app  
    

    Finally, head to the browser and go to http://localhost:8888

    So there we go. As you can see it's pretty straightforward to create a default Mongoose connection and use it in your application. You can test the disconnection script and event handler by terminating your Node process. In the terminal window running the Node app just hit Ctrl + C to kill the process.

From: http://theholmesoffice.com/mongoose-connection-best-practice/

posted on 2017-11-21 10:05  今夜太冷  阅读(187)  评论(0编辑  收藏  举报