首页 技术 正文
技术 2022年11月15日
0 收藏 643 点赞 4,990 浏览 3610 个字

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/

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,077
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,552
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,401
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,176
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,813
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,896