How can I connect to mongodb using express without mongoose?

I use the express framework and want to connect to mongodb without using mongoose, but with my own Mongodb nodejs driver. How can I do this without creating a new connection every time?

In order to process requests for receiving or sending, I am currently opening a new db connection for each request and closing it when the request is complete. Is there a better way to do this? Thanks in advance.

+4
source share
2 answers

Following the example of my comment, changing it so that the application handles errors rather than starting 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");
+4
source
var mongodb = require('mongodb');
var uri = 'mongodb://localhost:27017/dbname';

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

say connect.js, (connect.js) , http-.

+2

All Articles