node.js - Mongodb 和 Node.js 连接错误

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

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

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

最佳答案

您将针对每个请求打开一个新的数据库连接。您可以通过以下一种方法重新排列代码以创建一个连接和一个 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);
  });
}

关于node.js - Mongodb 和 Node.js 连接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23565420/

相关文章:

javascript - node.js 服务器读取文件顺序?

node.js - 查找数组 MongoDB 中的内容

java - 如何使用 Mongodb C++ 避免重复

node.js - MongoDB 请求 : Filter only specific field from embedded documents in embedded array

node.js - 如何从 Mongoose 主模型获取嵌套架构键?

javascript - Mongoose 保存不正确的值

node.js - Facebook 无法抓取我的安全网址 (Nginx)

javascript - Discord.js 搜索特定 channel 名称以将消息发送到(日志)

mongodb - MongoDB 的最佳 Web 框架?

node.js - Mongoose 嵌套 group by 对嵌套字段进行排序