javascript - 使用 MongoDB 数据库为每个查询打开一个新连接是好习惯吗?

标签 javascript node.js mongodb asynchronous

我正在创建一个将用户数据存储在 MongoDB 数据库中的网络服务器。 Web 请求背后的代码使用异步函数将文档插入数据库,但由于这些函数是异步的,这意味着对于每个请求都会与服务器建立一个新连接。

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()
    })
  })
}

我的印象是这样做不是最佳做法,但我想不出使用我上面使用的模块模型来做到这一点的方法。如有任何建议或建议,我们将不胜感激。

最佳答案

我在自己的研究中偶然发现了在每个查询上为 mongodb 使用新连接是最佳实践还是使用连接池。事实证明,mongodb 建议对大多数用例使用连接池。

引用自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 recommend calling MongoClient.connect once and reusing the database variable returned by the callback

我通常使用以下形式在触发查询时建立和重用连接:

// 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();
  }
};

触发查询:

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');
    });
  });
});

注意:可以手动确定池连接的最大数量(默认为 5?)。请参阅有关如何通过 mongodb url 设置打开的连接数的文档。

关于javascript - 使用 MongoDB 数据库为每个查询打开一个新连接是好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43698957/

相关文章:

javascript - 在 infiniteHits 小部件上触发 showMore (Algolia istantsearch.js)

javascript - 更新数组中的最后一项

Mongodb 具有排名/搜索计数

javascript - 在 html5 移动应用程序中使用 JavaScript 倒数计时器

Javascript:对象数组的数据验证

javascript - 使用 JS 或 JQuery 将所有大写字母转换为标题大小写的最有效方法?

javascript - 如何计算 javascript 中带有表情符号的字符串的正确长度?

javascript - Node.js 中的 Get/create 操作中未发现错误

node.js - Mongodb + Atlas : 'bad auth Authentication failed.' , 代码 : 8000,

mongodb - Mongoose增量值几次后错误