1

我正在运行节点 + express + mongojs。这是一个示例代码:

function mongoCallback(req, res) {
  "use strict";
  return function (err, o) {
    if (err) {
      res.send(500, err.message);
    } else if (!o) {
      res.send(404);
    } else {
      res.send(o);
    }
  };
}

var express, app, params, mongo, db;

express = require('express');
params = require('express-params');
app = express();
params.extend(app);

app.use("/", express.static('web'));

mongo = require('mongojs');

db = mongo.connect('mydb', ['inventory']);

app.get('/api/inventory', function (req, res) {
  db.inventory.find(mongoCallback(req, res));
});

app.listen(8000);
console.log('Listening on port 8000');

有时我忘记运行 mongod 并且尝试与数据库通信失败并出现“无法连接到 ...”错误。问题是启动 mongod 是不够的,已经存在的db对象似乎记得无法建立连接,因此服务器继续失败,即使 mongod 已经在运行。

所以,我想出了以下解决方案:

var express, app, params, mongo, db, api;

if (!String.prototype.startsWith) {
  String.prototype.startsWith = function (str) {
    "use strict";
    return this.lastIndexOf(str, 0) === 0;
  };
}

function setDB() {
  db = mongo.connect('IF', ['invoices', 'const', 'inventory']);
}

function mongoCallback(req, res, next, caller, secondTry) {
  return function (err, o) {
    if (err) {
      if (!secondTry && err.message && err.message.startsWith("failed to connect to")) {
        setDB();
        caller(req, res, next, true);
      } else {
        res.send(500, err.message);
      }
    } else if (!o) {
      res.send(404);
    } else {
      res.send(o);
    }
  };
}

express = require('express');
params = require('express-params');
app = express();
params.extend(app);

app.use("/", express["static"]('web'));

mongo = require('mongojs');

setDB();

api = {
  getInventory: function (req, res, next, secondTry) {
    db.inventory.find(mongoCallback(req, res, next, api.getInventory, secondTry));
  }
};

app.get('/api/inventory', api.getInventory);

app.listen(8000);
console.log('Listening on port 8000');

基本上,db如果请求因“连接失败”错误而失败,它会重新创建对象并重新运行请求。这仅适用于第一次失败。随后的失败将返回错误。

我根本不喜欢我的解决方案。一定有更好的方法。有什么建议么?

谢谢。

4

2 回答 2

2

“已经存在的 db 对象似乎记得无法建立连接”是什么意思?您的意思是如果您在运行 mongod 之前启动 express 应用程序,数据库上的查询会失败?由于您在 express 应用程序启动时连接到数据库,因此您应该首先运行 mongod。

如果您担心在初始连接后数据库出现故障并导致您的 CRUD 操作失败,您可以检查操作中的错误

db.inventory.find(function(err, docs) {
    // check err to see if there was a connection issue
});

然后如果有错误重新连接。

于 2012-08-31T14:34:45.073 回答
0

据我所知 mongodb 本机驱动程序允许设置{ auto_reconnect:true },您是否尝试过设置?

如果数据库根本没有运行,我不确定这会如何表现,mongoose.js例如缓存所有请求,直到数据库准备好并在成功连接后发出它们。

于 2012-08-31T14:49:56.940 回答