【发布时间】:2013-08-18 01:23:25
【问题描述】:
我尝试运行一个非常简单的“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。
有人能解释一下移动这 3 行代码所产生的区别吗?每次我想要一个不同的函数来访问数据库时,我真的需要建立一个新的连接吗?
【问题讨论】:
标签: javascript node.js mongodb express mongoose