0

Currently building an app with express and mongoDB.I find myself constantly questioning multiple things which I couldn't find a clear answer on. When we have the following (simplified) application:

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";
const express = require('express')
const app = express()

app.get('/', (req, res) => {

MongoClient.connect(url,(err, db) => {
  if (err) throw err;
  db.db("mydb").collection("customers").findOne({}, (err, result) => {
    if (err) throw err;
      // do useful stuff
    db.close();
  });
});

});

app.listen(3000, () => console.log('Example app listening on port 3000!'));

Questions:

  1. What is the most 'expensive' operation, is this opening the DB or doing the action on the DB like findOne/updateOne. (or is it more complicated than this?)
  2. If 2 user agents send a get request to / and the get route is executed twice does the mongoDB database makes 2 connections or can it do this on the same connection?
Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155
  • Let's not even get into a too broad discussion. Accept that others know better than you presently do and just follow it. – Neil Lunn Apr 26 '18 at 12:55
  • [How do I manage MongoDB connections in a Node.js web application ?](https://stackoverflow.com/questions/10656574/how-do-i-manage-mongodb-connections-in-a-node-js-web-application) - is what you basically need to simply accepting and following – Neil Lunn Apr 26 '18 at 12:55
  • Okay I didn't knew it was this open ended, that's probably why I coudn't find any material on the matter – Willem van der Veen Apr 26 '18 at 12:59
  • 1
    So `1` -- Don't do it because it's very expensive in terms of I/O on handshake alone. `2` - You are asking the database to open new connections on every request. If you do it like the common wisdom says however, then neither of these are an issue. Cost is at startup only and connections are managed in a pool, only being spawned when needed to fulfil requests – Neil Lunn Apr 26 '18 at 12:59
  • Dude you could write a book on this ( maybe I should talk to a publisher ). Just follow the same singleton pattern we all know works tried and true – Neil Lunn Apr 26 '18 at 13:00
  • Interest post (how to manage connections). So I basically make one connection which gets made when the express app boots up. Then I reuse this connection object for all my database interactions? – Willem van der Veen Apr 26 '18 at 13:05
  • Yes. Done in any number of ways, but usually in a modular design you simply want to store the connection result ( `MongoClient` instance ) within a variable to that module, and have a method to return that variable, or optionally connect where the value is not currently defined. That's the gist. There's some code examples and pointers to various modules that do this for you already. – Neil Lunn Apr 26 '18 at 13:09

0 Answers0