用express.js处理mongoose关系的正确方法是什么?

我有一个非常简单的“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; 

当它们在函数中声明时,脚本按预期运行,打印出从数据库中find的JSON对象。 当它们在testscript.js中定义但在方法范围之外时 ,程序挂在db.once('open', function callback () {...}); command db.once('open', function callback () {...}); command

有人可以通过移动这3行代码来了解一些差异吗? 每次我想要一个不同的函数来访问数据库,我真的需要build立一个新的连接吗?

如果你已经连接到数据库, once事件不会再次触发。 当全局连接(function之外)时,数据库已连接到整个NodeJs进程。

调用mongoose.connect('mongodb://localhost/test'); build立连接并打开它。

所以,而不是打开每个函数调用(这将是一个低效的方式来与MongoDB互动),当NodeJs应用程序启动时,立即connect ,并认为会有一段时间,连接可能不可用(因为它asynchronous),或者在连接完成(或超时)之前不要启动应用程序( listen )。 使用Mongoose,直到build立连接,所有的命令都被缓冲(但是这可能不是你想要的行为)。 如果您想知道连接何时完成,您可以使用open事件。

连接可以在这里find: mongoose.connection如果你使用connectfunction创build连接。

一旦连接打开,你可以使用它从你的popSingleData函数,而不使用once事件和callback。 有一个连接池自动维护。

有关连接的更多信息,请阅读此处 。