Mongodb和Node.js连接错误

时间:2014-05-09 13:06:46

标签: node.js mongodb mongoose httpserver

我是服务器端的新手。我刚开始使用node.js和mongodb。

示例代码:

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

运行我的代码时,它第一次运行,但是当我尝试刷新页面时,我收到此错误并且没有响应:

  

连接错误:{[错误:尝试打开未关闭的连接。]状态:1}

1 个答案:

答案 0 :(得分:2)

您正在为每个请求打开一个新的数据库连接。这里有一种方法可以重新排列代码以创建一个连接和一个Users对象,并在稍后的请求处理程序中使用它:

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