Answer the question
In order to leave comments, you need to log in
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
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.
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 questionAsk a Question
731 491 924 answers to any question