MongoError:应用程序使用节点关闭的连接。js的司机

时间:2022-03-14 07:00:47

Hi guys, need some help , have a problem when run this code :

大家好,需要帮助,运行这个代码有问题:

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

it works, but then appear this message =(:

它工作,但随后出现这个消息=(:

MongoError: Connection Closed By Application

1 个解决方案

#1


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

#1


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