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/

Mongoose Connection best practice的更多相关文章

  1. 报错mongoose.connection.db.collectionnames is not a function

    mongoose.connection.db.collectionNames方法已经无效 建议使用mongoose.connection.db.listCollections()

  2. mongoose中connect()、createConnection()和connection的区别和作用

    转文:原文 1 mongoose简介 在使用mongodb数据库开发项目中,nodejs环境下可能会使用到mongoose模块连接并操作mongodb数据库.mongoose模块相当于Java中的数据 ...

  3. mongoose数据库连接和操作

    var mongoose = require('mongoose') mongoose.connect('mongodb://localhost:27017/hometown'); var db = ...

  4. Nodejs之MEAN栈开发(三)---- 使用Mongoose创建模型及API

    继续开扒我们的MEAN栈开发之路,前面两节我们学习了Express.Jade引擎并创建了几个静态页面,最后通过Heroku部署了应用. Nodejs之MEAN栈开发(一)---- 路由与控制器 Nod ...

  5. Mongoose学习笔记

    #名词解释: Schema 一种以文件形式存储的数据库模型骨架,不具备对数据库操作的能力 Model 由Schema生成的模型,具有抽象属性和行为,能够操作数据库 Entity 由Model创建的实体 ...

  6. Node.js使用Mongoose包操作MongoDB数据库

    1. 安装Mongoose npm install mongoose 2. 使用 2.1 创建连接 var mongoose = require('mongoose'); mongoose.conne ...

  7. Nodejs学习笔记(十四)— Mongoose介绍和入门

    目录 简介 mongoose安装 连接字符串 Schema Model 常用数据库操作 插入 更新 删除 条件查询 数量查询 根据_id查询 模糊查询 分页查询 其它操作 写在之后... 简介 Mon ...

  8. mongoose 数据库操作 - 分页

    使用mongoose 加入分页方法,临时还没发现什么更好的方法,我使用的方法是,直接在源代码中加入 找到 node_modules/mongoose/lib/model.js打开这个文件.里面加入这段 ...

  9. nodejs+mongoose操作mongodb副本集实例

    继上一篇设置mongodb副本集之后,开始使用nodejs访问mongodb副本集: 1:创建项目     express 项目名称 2:npm install mongoose    安装mongo ...

随机推荐

  1. 关于bootstrap的treeview不显示多选(复选框)的问题,以及联动选择的问题,外加多选后取值

    最近做项目用到了treeview.因为涉及到多选的问题,很是棘手,于是乎,我决定查看原生JS,探个究竟.需要引用官方的bootstrap-treeview.js都知道吧,对于所需要引用的,我就不多说了 ...

  2. 【优化】COUNT(1)、COUNT(*)、COUNT(常量)、COUNT(主键)、COUNT(ROWID)等

    http://blog.itpub.net/26736162/viewspace-2136339/

  3. 网速4M等于多少KB/S,等于多少kbps

    4M=512KB/S=4096Kbps 1KB/S=8Kbps 8倍速 转:http://zhidao.baidu.com/link?url=8GAyhcY9BbVstQr8pE3I7QP_M53Km ...

  4. javascript 编辑网页

    javascript:document.body.contentEditable='true';document.designMode='on'; void 0 出处:http://zhidao.ba ...

  5. bash 脚本中分号的作用

    在Linux bash shell中,语句中的分号一般用作代码块标识 1.单行语句一般要用到分号来区分代码块.比如: weblogic@pmtest:/$if [ "$PS1" ] ...

  6. C#编程(五十五)----------HashSet和SortedSet

    集 饱含不重复元素的集合称为”集(set)”. .NET4包含两个集(HashSet<T>和SortedSet<T>),他们都实现ISet<T>接口.HashSet ...

  7. WordPress主题开发实例:get_term_by()获取指定分类链接

    根据名称获取链接 <?php //根据名称获取对应的id $term=get_term_by('name','新闻动态','category'); $term_id=$term->term ...

  8. python测试开发django-31.admin后台一对多操作ForeignKey

    前言 平常的网页上有很多一对多的场景,比如填写银行卡信息的时候,会从银行列表下拉框选择对应的银行信息.一般会建两张表,一张表放银行的信息,一张表放银行卡信息. 每个银行可以对应多个银行卡,每个银行卡只 ...

  9. python测试开发django-20.添加创建时间DateTimeField

    前言 我们在admin后台发布一篇文章的时候,一般会有创建时间和最后更新时间这2个字段,创建时间就是第一次编辑文章的时候自动添加的,最后更新时间就是每次修改文章的内容后自动更新 在models.py建 ...

  10. Linux学习19-gitlab配置邮箱postfix(新用户激活邮件)

    前言 gitlab新增新用户有两种方式,第一种可以用户主动注册(自己设置密码):第二种也可以通过root管理员用户直接添加用户,发个邮件到用户的邮箱里,收到邮件后激活. 如果是第二种方式添加新用户的话 ...