我有一个服务器启动并运行,没有错误被抛出。我从一个mongodb流式传输数据。当数据完成流式传输时,我想调用'close',然后断开mongo数据库。关闭与Node.js的Mongoose连接
下面是我的代码。当我尝试连接到服务器时,第一个请求成功,但任何其他请求都失败。
当我试图检查是否mongodb被断开时,我发现它不是。如何使用mongoose.connection.close()
以及何时会失败?
var http = require('http')
, url = require('url')
, mongoose = require('mongoose')
, Schema = mongoose.Schema
, server, n;
server = http.createServer(function(request, response) {
var path = url.parse(request.url).pathname.slice(0, 4);
n = url.parse(request.url).pathname.slice(5);
// connect to mongo
mongoose.set('debug', true);
mongoose.connect('localhost', 'lotsOfNumber');
mongoose.connection.on('error', function(err) {
console.error('connection error: ' + err);
});
mongoose.connection.on('open',function() {
var stuff = mongoose.model('numbersHere', new Schema({serialNumber: Number}, {safe: true}));
switch (path) {
case '/slq':
var stream = stuff.find({}).limit(1).skip(n).sort('field value').stream();
stream.on('error', function(err) {
console.error("Error trying to stream from collection:" + err);
});
stream.on('data', function(doc) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write(doc.value.toString() + '\n', 'utf8');
response.end();
});
stream.on('close', function() {
mongoose.connection.close();
mongoose.connection.on('close', function() {console.log('closed');});
});
break;
default:
console.log('nothing');
mongoose.connection.close();
break;
}
});
});
server.listen(8080);
任何帮助表示赞赏。
FWIW当删除'mongoose.connection'并改为使用'var db = mongoose.connect('localhost','m101',{server:{poolSize:1}})时,问题就消失了。 db.on('error',console.error.bind(console,'无法连接到mongo服务器'));'。通过将mongoose.connection分配给db并避免'on('open'...)'mongoose确实关闭了数据库 – user1460015