我有一个非常简单的“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 () {...}); command
.
有人可以解释一下移动这三行代码所产生的差异吗?每次我想要不同的函数访问数据库时,我真的需要建立一个新连接吗?