javascript - Is opening a new connection for each query with a MongoDB database good practise? - Stack Overflow

I'm creating a web server that stores a user's data in a MongoDB database. The code behind th

I'm creating a web server that stores a user's data in a MongoDB database. The code behind the web requests uses asynchronous functions to insert a document into the database, but because these functions are asynchronous it means that for every request a new connection is made with the server.

exports.create_user = function(username, password, callback) {
  mongo.connect(url, function(err, db) {
    db.collection('users').insertOne({username: username, password: password}, function(err, result) {
      callback(result)
      db.close()
    })
  })
}

I'm under the impression that doing it this way is not the best practise, but I can't think a way to do it using the module model that I'm using above. Any suggestions or advice would be appreciated.

I'm creating a web server that stores a user's data in a MongoDB database. The code behind the web requests uses asynchronous functions to insert a document into the database, but because these functions are asynchronous it means that for every request a new connection is made with the server.

exports.create_user = function(username, password, callback) {
  mongo.connect(url, function(err, db) {
    db.collection('users').insertOne({username: username, password: password}, function(err, result) {
      callback(result)
      db.close()
    })
  })
}

I'm under the impression that doing it this way is not the best practise, but I can't think a way to do it using the module model that I'm using above. Any suggestions or advice would be appreciated.

Share Improve this question asked Apr 29, 2017 at 18:09 CarlCarl 7936 silver badges19 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

I stumbled upon this on my own research whether to use a new connection for mongodb on each query is the best practice or to use connection pooling. Turns out, that mongodb suggests connection pooling for most use-cases.

Citing from the docs:

A Connection Pool is a cache of database connections maintained by the driver so that connections can be re-used when new connections to the database are required. To reduce the number of connection pools created by your application, we remend calling MongoClient.connect once and reusing the database variable returned by the callback

I am usually using the following form to establish and reuse a connection while firing queries:

// db.js
import { MongoClient } from 'mongodb';

// this will hold our cached database connection, which will itself hold multiple connections in a pool to be used
let connection,
  database;

export {
  connect: (next) => {
    // already established? => return connection
    if (database) return next(undefined, database);

    // establish connection
    MongoClient.connect('http://localhost:27017/admin', (err, db) => {
      if (err) return next(err);

      // save connection
      connection = db;

      // connect to database
      database = db.db('myDatabase');

      // call callback
      next(undefined, database);
    });
  },

  disconnect: (next) => {
    if (!connection) return next();

    // close connection
    connection.close();
    next();
  }
};

Firing queries:

import db from './db';

db.connect((err, db) => {
  if (err) return next(err);

  db.collection('myUsers').insertOne({name: 'test'}, (err) => {
    if (err) throw err;

    db.disconnect((err) => {
      if (err) throw err;

      console.log('Everything finished, database connection closed');
    });
  });
});

Note: It is possible to determine the maximum amount of pooled connections manually (afaik the default is 5?). Refer to the docs about how to set the amount of opened connections via the mongodb url.

By doing db.close() you can close the connection, If you don't close your connection, event loop will keep the connection open and your process will not exit. If you are building a web server where your process will not be terminated, it's not necessary for you to close the connection. For a reference node-mongodb-native

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744674714a4587258.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信