user1460015
user1460015

Reputation: 2003

Closing Mongoose connection with Node.js

I have a server up and running with no errors being thrown. I am streaming data from a mongodb. When the data is done streaming I want to call 'close' and then disconnect the mongo database.

Below is the code that I have. When I try to connect to the server a first request succeeds but any additional requests fail.

When I attempted to check if the mongodb was being disconnected I found out that it wasn't.

How do you use a mongoose.connection.close() and when will it fail?

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);

Any help is appreciated.

Upvotes: 2

Views: 8527

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

I've always used a pattern like:

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

But you shouldn't be connecting and disconnecting on each request like you are. Instead, connect during your application start up and disconnect during shutdown.

mongoose.connect opens a pool of connections that concurrent requests can share.

Upvotes: 8

Related Questions