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/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
2014-11-21 C++中delete和delete[]的区别
2005-11-21 从绝望中寻找希望,人生必将辉煌