2012-11-02 71 views
2

我有一个服务器启动并运行,没有错误被抛出。我从一个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); 

任何帮助表示赞赏。

+0

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

回答

8

我一直使用类似的模式:

mongoose.connect('localhost', 'lotsOfNumber'); 
... 
mongoose.disconnect(); 

但你不应该连接和断开每个请求喜欢你。相反,在应用程序启动期间连接并在关机期间断开连接。

mongoose.connect打开并发请求可以共享的连接池。

+0

谢谢。我移动了'http.createServer'之外的db连接。 – user1460015

+1

“但是你不应该像每个请求那样连接和断开连接,而应该在应用程序启动时连接并在关闭期间断开连接。” 这就是我一直在寻找:) –