Jerlam
Jerlam

Reputation: 1081

How to use mongoClient.connect with express?

I am getting started with mongoDB and I have to say that the official documentation is not that great to see how to implement it with nodejs.

I don't really know how to structure my server file to add mongoClient.connect, should my whole server be written inbeetwen the mongoClient.connect function in order to have access to the db, like in this boilerplate? I am using nodeJS/express.

If you know any good boilerplate, or anything, that could show me the structure of a backend with an implementation of mongoDB, I would really appreciate it. Every time I find something about mongoDB, it is actually about mongooooose!!

Upvotes: 1

Views: 3721

Answers (2)

DiegoMMF
DiegoMMF

Reputation: 139

I've found several ways of doing it, even in mongoDB's official pages.

By far, I prefer this one (not mine, source below) where you instantiate the connection in one file and export it and the database/client to the server file where express is instantiated:

(I copied only what's important, without error handling)

// database.js

const MongoClient = require('mongodb').MongoClient;

let _db; //'_' private

const mongoConnect = function(callback) {
    MongoClient.connect(
        'mongodb://localhost:27017',
        { useUnifiedTopology: true }
        )
        .then(client => {
            _db = client.db('onlineshopping');
            callback();
        })
        .catch(error => {
            console.log(err);
            throw new Error('DB connection failed...');
        });
}

const getDB = () => {
    if (_db) {
        return _db;
    } else {
        throw new Error('DB connect failed');
    }
}

exports.mongoConnect = mongoConnect;
exports.getDB = getDB;

// index.js

const express = require('express');
const app = express();
const mongoConnect = require('./util/database').mongoConnect;

// ...

mongoConnect(() => {
    app.listen(3000);
})

Source: https://github.com/TinaXing2012/nodejs_examples/blob/master/day9/util/database.js Corresponding to this YouTube course that I recommend in this topic: https://www.youtube.com/watch?v=hh-gK0_HLEY&list=PLGTrAf5-F1YLBTY1mToc_qyOiZizcG_LJ&index=98

Other alternatives from mongoDB official repos, are:

Upvotes: 1

Jerlam
Jerlam

Reputation: 1081

After further reasearch, here is what I was looking for, for those who wonder like me how to implement MongoDB (and not mongoose) with Express:

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) throw err;

  db = database;

  // Start the application after the database connection is ready
  app.listen(3000);
  console.log("Listening on port 3000");
});

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

Upvotes: 2

Related Questions