C
C
Cat Scientist2016-03-08 18:07:51
MongoDB
Cat Scientist, 2016-03-08 18:07:51

How to properly connect to MongoDB in NodeJS?

Open a new DB connection on every web server request, or open a connection on application initialization and use the same connection everywhere?

var express = require('express');
var app = express();

app.locals.MongoDB = require('mongodb');
app.locals.MongoClient = app.locals.MongoDB.MongoClient;

// [1] Здесь может быть роутинг. Или:

app.locals.MongoClient.connect('mongodb://localhost/test')
.then(db => {

  // Соединение с БД установлено и теперь доступно в любом роуте:
  app.locals.db = db;

  // [2] ... и роутинг здесь.

  return new Promise((resolve, reject) => {
    var port = process.env.PORT || 8080;
    app.listen(port, () => {
      resolve(`App listening on http://localhost:${port}/`);
    });
  });
}, console.log)
.then(console.log, console.log);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
U
un1t, 2016-03-08
@eruditecat

In short, call the connection once, it creates a connection pool. Write a singleton. If you call a connection for every request, then under heavy load, the application will die.

A
Alexander Wolf, 2016-03-08
@mannaro

Usually, several connections (pool) are opened at once when the application starts, then the load is distributed over them (additional connections are created/stopped). I would suggest to use Mongoose, it will take this problem away from you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question