Question

I am very new to the server side. I just started with node.js and mongodb.

Example code:

var http = require('http');
var mongoose = require('mongoose');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'application/json; charset=utf-8'});

  mongoose.connect('mongodb://localhost/bookmarks');
  var db = mongoose.connection;
  db.on('error', console.error.bind(console, 'connection error:'));

  db.once('open', function callback () {
    // console.log('Running');

    var Users = mongoose.model('users', { name: String, lastname: String, yas: Number,   yer:String });

    Users.find().lean().exec(function(err,users) {
      // console.log(JSON.stringify(users));
      var sonuc=JSON.stringify(users);

      console.log(sonuc);
      res.end(sonuc);
    });
  });
}).listen(1337,'127.0.0.1');

When running my code, it works the first time, but when I try to refresh the page I get this error and there is no response:

connection error: { [Error: Trying to open unclosed connection.] state: 1 }

Was it helpful?

Solution

You're opening a new database connection on every request. Here's one way you could rearrange your code to create one connection and one Users object, and use that later in the request handler:

var http = require('http');
var mongoose = require('mongoose');

// we want Users to be in the global scope here, not in a function
// that way different functions can both see the same variable
var Users = null; 

mongoose.connect('mongodb://localhost/bookmarks');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));

// By placing Users and createServer inside the db.once('open') callback,
// we wait till mongo is ready before letting the http handler query users:
db.once('open', function(){
  console.log('Running');
  // now overwrite the already defined Users variable:
  Users = mongoose.model('users', { name: String, lastname: String, yas: Number,   yer:String });
  http.createServer(function (req, res) {
    findUsers(function(err, results){
      if(err){
        res.writeHead(500);
        res.end();
      } else {
        res.writeHead(200, {'Content-Type': 'application/json; charset=utf-8'});
        res.end(results);
      };
    });
  }).listen(1337,127.0.0.1);
});

function findUsers(callback){
  Users.find().lean().exec(function(err,users) {
    // console.log(JSON.stringify(users));
    var sonuc=JSON.stringify(users);
    console.log(sonuc);
    //res.end(sonuc);
    callback(err, sonuc);
  });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top