【问题标题】:How can I connect to mongodb using express without mongoose?如何在没有猫鼬的情况下使用 express 连接到 mongodb?
【发布时间】:2016-07-22 08:28:22
【问题描述】:

我正在使用 express 框架,并且想在不使用 mongoose 的情况下连接到 mongodb,但使用本机 nodejs Mongodb 驱动程序。在不每次都创建新连接的情况下如何做到这一点?

为了处理 get 或 post 请求,我目前为每个请求打开一个到数据库的新连接,并在请求完成时关闭它。有一个更好的方法吗?提前致谢。

【问题讨论】:

  • 我不知道您每次都必须真正打开一个新连接。查看mongodb.github.io/node-mongodb-native/driver-articles/…
  • 但在这种情况下,如果无法建立与 db 的连接,那么 out 服务器本身将不会启动。
  • 基本模式仍然有效。我会跟进这个问题的答案。

标签: node.js mongodb express mongoose


【解决方案1】:

按照我评论中的示例,对其进行修改,以便应用处理错误而不是无法启动服务器。

var express = require('express');
var mongodb = require('mongodb');
var app = express();

var MongoClient = require('mongodb').MongoClient;
var dbURL = "mongodb://localhost:27017/integration_test";
var db;

// Initialize connection once
MongoClient.connect(dbURL, function(err, database) {
  if(err) return console.error(err);

  db = database;

  // the Mongo driver recommends starting the server here 
  // because most apps *should* fail to start if they have no DB.
  // If yours is the exception, move the server startup elsewhere. 
});

// Reuse database object in request handlers
app.get("/", function(req, res, next) {
  var collection = "replicaset_mongo_client_collection";
  db.collection(collection).find({}, function(err, docs) {
    if(err) return next(err);
    docs.each(function(err, doc) {
      if(doc) {
        console.log(doc);
      }
      else {
        res.end();
      }
    });
  });
});

app.use(function(err, req, res){
  // handle error here.  For example, logging and 
  // returning a friendly error page
});

// Starting the app here will work, but some users 
// will get errors if the db connection process is slow.  
app.listen(3000);
console.log("Listening on port 3000");

【讨论】:

  • 如果我使用猫鼬怎么办?
  • @SudhirKaushik 如果你是?这个答案是针对“没有猫鼬我该怎么做”这个问题。
  • 当你回头看你的答案并觉得“我可以用更好的方式说出来”时,它是如此尴尬。无论如何,当我尝试使用猫鼬进行设置时,我的上述问题有点自私。应该问一个不同的问题。没关系
  • @SudhirKaushik 检查this。有大量使用猫鼬的教程。感谢 Paul,分享这个 sn-p。
【解决方案2】:
var mongodb = require('mongodb');
var uri = 'mongodb://localhost:27017/dbname';

module.exports = function(callback) {
  mongodb.MongoClient.connect(uri, callback);
};

在一个文件中添加这个 sn-p,比如 connect.js,然后在你声明你的 http 请求函数的文件中需要这个文件(connect.js)。

【讨论】:

  • 但是这个 sn-p 每次都会发出一个新的连接请求,这是我们不想要的
  • 在我看来这是正确的方法,即在发出 http 请求之前检查连接是否建立。
  • 我相信要求这个 sn-p 将被缓存在应用程序中,它不会每次都发出新请求。
猜你喜欢
  • 2022-11-22
  • 2020-05-03
  • 2020-04-08
  • 1970-01-01
  • 2020-04-03
  • 2016-04-29
  • 2019-10-03
  • 2014-05-19
相关资源
最近更新 更多