Mongoose Connection best practice
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.jsapp.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 definitionStarting 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的更多相关文章
- 报错mongoose.connection.db.collectionnames is not a function
mongoose.connection.db.collectionNames方法已经无效 建议使用mongoose.connection.db.listCollections()
- mongoose中connect()、createConnection()和connection的区别和作用
转文:原文 1 mongoose简介 在使用mongodb数据库开发项目中,nodejs环境下可能会使用到mongoose模块连接并操作mongodb数据库.mongoose模块相当于Java中的数据 ...
- mongoose数据库连接和操作
var mongoose = require('mongoose') mongoose.connect('mongodb://localhost:27017/hometown'); var db = ...
- Nodejs之MEAN栈开发(三)---- 使用Mongoose创建模型及API
继续开扒我们的MEAN栈开发之路,前面两节我们学习了Express.Jade引擎并创建了几个静态页面,最后通过Heroku部署了应用. Nodejs之MEAN栈开发(一)---- 路由与控制器 Nod ...
- Mongoose学习笔记
#名词解释: Schema 一种以文件形式存储的数据库模型骨架,不具备对数据库操作的能力 Model 由Schema生成的模型,具有抽象属性和行为,能够操作数据库 Entity 由Model创建的实体 ...
- Node.js使用Mongoose包操作MongoDB数据库
1. 安装Mongoose npm install mongoose 2. 使用 2.1 创建连接 var mongoose = require('mongoose'); mongoose.conne ...
- Nodejs学习笔记(十四)— Mongoose介绍和入门
目录 简介 mongoose安装 连接字符串 Schema Model 常用数据库操作 插入 更新 删除 条件查询 数量查询 根据_id查询 模糊查询 分页查询 其它操作 写在之后... 简介 Mon ...
- mongoose 数据库操作 - 分页
使用mongoose 加入分页方法,临时还没发现什么更好的方法,我使用的方法是,直接在源代码中加入 找到 node_modules/mongoose/lib/model.js打开这个文件.里面加入这段 ...
- nodejs+mongoose操作mongodb副本集实例
继上一篇设置mongodb副本集之后,开始使用nodejs访问mongodb副本集: 1:创建项目 express 项目名称 2:npm install mongoose 安装mongo ...
随机推荐
- 用ViewPager实现一个程序引导界面
下面使用ViewPager来实现一个程序引导的demo: 一般来说,引导界面是出现第一次运行时出现的,之后不会再出现.所以需要记录是否是第一次使用程序,办法有很多,最容易想到的就是使用SharedPr ...
- Entity framework 增加默认执行时间
public partial class ProductionSupportEntities : DbContext { public ProductionSupportEntities() : ba ...
- 【linux】linux 下 shell命令 执行结果赋值给变量【两种方式】
方法1:[通用方法] 使用Tab键上面的反引号 例子如下: find命令 模糊查询在/apps/swapping目录下 查找 文件名中包含swapping并且以.jar结尾的文件 使用反引号 引住命令 ...
- python测试开发django-16.JsonResponse返回中文编码问题
前言 django查询到的结果,用JsonResponse返回在页面上显示类似于\u4e2d\u6587 ,注意这个不叫乱码,这个是unicode编码,python3默认返回的编码 遇到问题 接着前面 ...
- 手机也需“绿色环保”,省电类APP或将成为“标配”?
随着移动APP的大幅添加.非常多用户发现,这手机耗电量是越来越大了,在各种娱乐应用.办公应用.社交应用的冲击下,以往两天充一次电都OK.如今一天充一次还不够用,因为续航能力变弱.这也为用户带来 ...
- java collection.frequency方法
collection.frequency方法,可以统计出某个对象在collection中出现的次数 比如: frequency(Collection<?> c, Object o) ...
- 新闻编辑室第三季/全集The Newsroom迅雷下载
第三季 The Newsroom Season 3 (2014)看点:今日他们终于公布了续订第三季的消息,但同时也宣称第三季将会是<新闻编辑室>的最终季,对剧迷们来说可谓苦乐参半.讲述了一 ...
- Lua的文件操作
先简单介绍一下被迫使用Lua的IO的情境: 游戏支持玩家自定义上传头像,在排行榜中会显示玩家列表(包括本服.跨服),原有的做法是先检测CCUserDefault中是否存在指定图片的key以及它的状态. ...
- 国家code和区号计算
因为项目中要用到这个功能.实现类似微信注冊时能够选择国家并得到对应的区号.还要推断号码正确与否的正则. 找到了 libPhoneNumber-iOS 标准化电话号码库 https://github.c ...
- 腾讯Bugly2015年移动应用质量大数据报告 原 荐
在这份报告中,腾讯Bugly和腾讯优测会对2015年Android和iOS平台上的应用质量进行详细盘点,帮助你了解你的产品质量在行业中处于什么位置. 首先,让我们从整体上,回顾一下2015年度的应用和 ...