Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I connect to mongodb using express without mongoose?

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.

like image 265
Saurabh Verma Avatar asked Apr 02 '16 15:04

Saurabh Verma


People also ask

Is it mandatory to use Mongoose with Node application?

It's not mandatory to use Mongoose over the MongoDB Native API. However, there are some benefits to doing so.

Why do we need Mongoose for MongoDB?

The benefit of using Mongoose is that we have a schema to work against in our application code and an explicit relationship between our MongoDB documents and the Mongoose models within our application. The downside is that we can only create blog posts and they have to follow the above defined schema.


1 Answers

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 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");
like image 163
Paul Avatar answered Oct 27 '22 12:10

Paul