如何在没有猫鼬的情况下使用Express连接到mongodb? [英] How can I connect to mongodb using express without mongoose?

查看:70
本文介绍了如何在没有猫鼬的情况下使用Express连接到mongodb?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用express框架,并希望不使用mongoose而是使用本机nodejs Mongodb驱动程序来连接到mongodb.如何做到这一点而又不必每次都建立新的连接?

I am using the express framework and would like to connect to a mongodb without using mongoose, but with the native nodejs Mongodb driver. How can I do this without creating a new connection every time?

要处理获取或发布请求,我目前为每个请求打开一个与数据库的新连接,并在请求完成时将其关闭.有一个更好的方法吗?预先感谢.

To handle get or post requests I currently open a new connection to the db for every request and close it on completion of the request. Is there a better way to do this? Thanks in advance.

推荐答案

按照我的注释中的示例进行修改,以便应用程序能够处理错误而不是无法启动服务器.

Following the example from my comment, modifying it so that the app handles errors rather than failing to start the server.

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

这篇关于如何在没有猫鼬的情况下使用Express连接到mongodb?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆