When to close MongoDB database connection in Nodejs

前端 未结 8 639
一整个雨季
一整个雨季 2020-11-28 21:56

Working with Nodejs and MongoDB through Node MongoDB native driver. Need to retrieve some documents, and make modification, then save them right back. This is an example:

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 22:29

    Based on the suggestion from @mpobrien above, I've found the async module to be incredibly helpful in this regard. Here's an example pattern that I've come to adopt:

    const assert = require('assert');
    const async = require('async');
    const MongoClient = require('mongodb').MongoClient;
    
    var mongodb;
    
    async.series(
        [
            // Establish Covalent Analytics MongoDB connection
            (callback) => {
                MongoClient.connect('mongodb://localhost:27017/test', (err, db) => {
                    assert.equal(err, null);
                    mongodb = db;
                    callback(null);
                });
            },
            // Insert some documents
            (callback) => {
                mongodb.collection('sandbox').insertMany(
                    [{a : 1}, {a : 2}, {a : 3}],
                    (err) => {
                        assert.equal(err, null);
                        callback(null);
                    }
                )
            },
            // Find some documents
            (callback) => {
                mongodb.collection('sandbox').find({}).toArray(function(err, docs) {
                    assert.equal(err, null);
                    console.dir(docs);
                    callback(null);
                });
            }
        ],
        () => {
            mongodb.close();
        }
    );
    

提交回复
热议问题