我尝试运行一个非常简单的“server.js”设置:
var express = require('express'),
wines = require('./routes/testscripts');
var app = express();
app.get('/first_test', wines.popSingleData);
app.listen(3000);
console.log('Listening on port 3000...');
这是设置为连接到 localhost:3000
当我导航到 localhost:3000/first_test
时,它会调用 testscript.js 中的“popSingleData”方法:
...
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
console.log('include called');
exports.popSingleData = function(req, res) {
// var mongoose = require('mongoose');
// mongoose.connect('mongodb://localhost/test');
// var db = mongoose.connection;
console.log('function called');
db.on('error', console.error.bind(console, 'connection error:'));
console.log('error handler set');
db.once('open', function callback () {
//yay!
console.log("DB Opened");
var someSchema = require('../models/someSchema');
someSchema.find(function (err, found){
if (err)
{
console.log('err');
}
if(found.length != 0)
{
console.log("Found Data:");
console.log(found);
for( var i = 0; i < found.length; i++)
{
res.jsonp((found[i]));
}
}
});
});
};
...
导致问题的行是前 3 行:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
在函数中声明它们时,脚本会按预期运行,打印出从数据库中找到的 JSON 对象。当它们在 testscript.js 中定义,但在方法的范围之外,程序会卡在 db.once('open', function callback () {...}) ;命令
。
有人能解释一下移动这 3 行代码所产生的区别吗?每次我想要一个不同的函数来访问数据库时,我真的需要建立一个新的连接吗?
最佳答案
如果您已经连接到数据库,once
事件将不会再次触发。全局连接时(函数外部),整个 NodeJs 进程的数据库已经连接。
调用 mongoose.connect('mongodb://localhost/test');
建立连接并打开它。
所以,不是在每次函数调用时都打开它(这将是与 MongoDB 交互的一种低效方式)connect
在 NodeJs 应用程序启动时立即打开,并考虑会有一段时间连接可能不可用(因为它是异步的),或者在连接完成(或超时)之前不要启动应用程序(listen
)。使用 Mongoose,在建立连接之前,所有命令都会被缓冲(但这可能不是您想要的行为)。如果您想知道连接何时完成,可以使用 open
事件。
连接在这里找到:mongoose.connection
如果您使用 connect
函数来创建连接。
连接打开后,您可以从 popSingleData
函数中使用它,而无需使用 once
事件和回调。有一个自动维护的连接池。
有关连接的更多信息,请阅读 here .
关于javascript - 用 express.js 处理 Mongoose 连接的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18259725/