How do I manage MongoDB connections in a Node.js web application?

前端 未结 11 2316
旧巷少年郎
旧巷少年郎 2020-11-22 02:42

I\'m using the node-mongodb-native driver with MongoDB to write a website.

I have some questions about how to manage connections:

  1. Is it enough using

11条回答
  •  隐瞒了意图╮
    2020-11-22 03:02

    Manage mongo connection pools in a single self contained module. This approach provides two benefits. Firstly it keeps your code modular and easier to test. Secondly your not forced to mix your database connection up in your request object which is NOT the place for a database connection object. (Given the nature of JavaScript I would consider it highly dangerous to mix in anything to an object constructed by library code). So with that you only need to Consider a module that exports two methods. connect = () => Promise and get = () => dbConnectionObject.

    With such a module you can firstly connect to the database

    // runs in boot.js or what ever file your application starts with
    const db = require('./myAwesomeDbModule');
    db.connect()
        .then(() => console.log('database connected'))
        .then(() => bootMyApplication())
        .catch((e) => {
            console.error(e);
            // Always hard exit on a database connection error
            process.exit(1);
        });
    

    When in flight your app can simply call get() when it needs a DB connection.

    const db = require('./myAwesomeDbModule');
    db.get().find(...)... // I have excluded code here to keep the example  simple
    

    If you set up your db module in the same way as the following not only will you have a way to ensure that your application will not boot unless you have a database connection you also have a global way of accessing your database connection pool that will error if you have not got a connection.

    // myAwesomeDbModule.js
    let connection = null;
    
    module.exports.connect = () => new Promise((resolve, reject) => {
        MongoClient.connect(url, option, function(err, db) {
            if (err) { reject(err); return; };
            resolve(db);
            connection = db;
        });
    });
    
    module.exports.get = () => {
        if(!connection) {
            throw new Error('Call connect first!');
        }
    
        return connection;
    }
    

提交回复
热议问题