MongoError:使用node.js驱动程序通过应用程序关闭连接

时间:2014-04-09 22:33:46

标签: node.js mongodb

大家好,需要一些帮助,运行此代码时遇到问题:

MongoClient.connect('mongodb://localhost:27017/school',function  (err,db) {
    if(err) throw err;
    var query = {};
    var cursor = db.collection('students').find(query);
        cursor.each(function  (err,doc) {
            if(err) throw err;
            if(doc==null) return db.close();
            //Processing doc to update
            db.collection('students').update({"_id":doc["_id"]},{$set:{"scores":doc.scores}},function  (err,result) {
                if(err) throw err;
            });
        });

可行,但随后显示此消息=(:

MongoError: Connection Closed By Application

1 个答案:

答案 0 :(得分:4)

MongoClient.connect('mongodb://localhost:27017/school',function  (err,db) {
if(err) throw err;
var query = {};
var cursor = db.collection('students').find(query);
    cursor.each(function  (err,doc) {
        if(err) throw err;
        if(doc==null) return db.close();
        //Processing doc to update
        db.collection('students').update({"_id":doc["_id"]},{$set:{"scores":doc.scores}},function  (err,result) {
            if(err) throw err;
            db.close(); //this line was missing!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        });
    });