如何在没有猫鼬的情况下使用快递连接到mongodb?

Sau*_*rma 7 mongoose mongodb node.js express

我正在使用快速框架,并希望连接到mongodb而不使用mongoose,但使用本机nodejs Mongodb驱动程序.如何在不创建新连接的情况下执行此操作?

为了处理get或post请求,我当前为每个请求打开一个与db的新连接,并在请求完成时关闭它.有一个更好的方法吗?提前致谢.

Pau*_*aul 8

按照我的评论示例,修改它以便应用程序处理错误而不是无法启动服务器.

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

var MongoClient = require('mongodb').MongoClient;
var db;

// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/integration_test", 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) {
  db.collection("replicaset_mongo_client_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");
Run Code Online (Sandbox Code Playgroud)

  • @SudhirKaushik如果你是什么?这个答案是关于"如何在没有猫鼬的情况下做到这一点"的问题. (4认同)
  • 当你回顾你的答案并觉得“我可以用更好的方式说出来”时,它是如此尴尬。无论如何,我上面的问题有点自私,因为我试图使用猫鼬进行设置。应该问一个不同的问题。没关系 (2认同)
  • @SudhirKaushik 检查[这个](https://codeburst.io/building-a-rest-api-using-mongo-db-75cac3403fab)。有大量使用 mongoose 的教程。感谢保罗分享这个片段。 (2认同)