如何有效地关闭数据库连接(mongodb和节点)

时间:2015-08-19 03:46:55

标签: node.js mongodb

我有一个小程序,它读取每条记录并更新每条记录。鉴于节点和回调的异步性质。什么是关闭数据库连接的有效和正确的方法?

示例程序:

var MongoClient = require('mongodb').MongoClient;
var updateCount = 0;

MongoClient.connect('mongodb://localhost:27017/school', function(err, db) {
    if(err) throw err;

    var query = { };
    // get all the students in the database 
    var cursor = db.collection('students').find(query);

    cursor.each(function(err, doc) {
        if(err) throw err;

        if(doc == null) {
            return;
        }

        // filter out only the homework scores
        var homeworksOnly = doc.scores.filter(function(scores){
            if (scores.type === "homework") return true;
            return false;
        })

        // filter out the non homework scores
        var notHomeWorks = doc.scores.filter(function(scores){
            if (scores.type !== "homework") return true;
            return false;
        })

        // sort the homework score to remove the min score from the list.
        homeworksOnly.sort(function(a,b){
            if (a.score > b.score) return 1;
            if (b.score > a.score) return -1;
            return 0;
        });

        console.log("Before removing the min score"+doc._id);
        console.dir(homeworksOnly);
        console.log("After removing the min score"+doc._id);
        homeworksOnly.splice(0,1);
        console.dir(homeworksOnly);
        console.log("Merge the homework with other scores"+doc._id);
        var newScores = homeworksOnly.concat(notHomeWorks);
        console.dir(newScores);
        console.log("*****");

        // Now update the database for this student with the new scores
        var search = {"_id":doc._id};
        var operator = { '$set' : { 'scores' : newScores } };

        db.collection('students').update(search, operator, function(err, updated) {
            if(err) throw err;

            updateCount++;
            console.dir("Successfully updated " + updated + " document! count: "+updateCount);
        });

    });
});

现在该程序可以运行,但是我需要按Ctrl + C来终止程序。有没有办法知道所有回调都已完成,以便程序可以终止?

2 个答案:

答案 0 :(得分:0)

更新语句完成后,使用

db.collection('students')。update(搜索,运算符,函数(错误,更新){         if(err)throw err;

    updateCount++;
    console.dir("Successfully updated " + updated + " document! count: "+updateCount);
});

db.close();

答案 1 :(得分:0)

有更好的库可以与nodejs集成以更好地处理回调流程,但只需使用基本驱动程序作为依赖项,您只需要基本的node stream接口已经内置到游标中

这允许.pause().resume()在处理时进行流量控制,在光标流完成时允许“结束”事件:

var MongoClient = require('mongodb').MongoClient;
var updateCount = 0;

MongoClient.connect('mongodb://localhost:27017/school', function(err, db) {
    if(err) throw err;

    var query = { };
    // get all the students in the database 
    var cursor = db.collection('students').find(query);

    // called on errors
    cursor.on("error",function(err) {
      throw err;
    });

    // called on stream complete
    cursor.on("end",function() {
      db.close();
    });

    // process each document in the stream
    cursor.on("data",function(data) {

        cursor.pause();     // stops the cursor stream while processing

        // filter out only the homework scores
        var homeworksOnly = doc.scores.filter(function(scores){
            if (scores.type === "homework") return true;
            return false;
        })

        // filter out the non homework scores
        var notHomeWorks = doc.scores.filter(function(scores){
            if (scores.type !== "homework") return true;
            return false;
        })

        // sort the homework score to remove the min score from the list.
        homeworksOnly.sort(function(a,b){
            if (a.score > b.score) return 1;
            if (b.score > a.score) return -1;
            return 0;
        });

        console.log("Before removing the min score"+doc._id);
        console.dir(homeworksOnly);
        console.log("After removing the min score"+doc._id);
        homeworksOnly.splice(0,1);
        console.dir(homeworksOnly);
        console.log("Merge the homework with other scores"+doc._id);
        var newScores = homeworksOnly.concat(notHomeWorks);
        console.dir(newScores);
        console.log("*****");

        // Now update the database for this student with the new scores
        var search = {"_id":doc._id};
        var operator = { '$set' : { 'scores' : newScores } };

        db.collection('students').update(search, operator, function(err, updated) {
            if(err) throw err;

            updateCount++;
            console.dir("Successfully updated " + updated + " document! count: "+updateCount);

            cursor.resume();        // restarts the stream processing now we are done
        });

    });

});