简体   繁体   中英

connection doesn't close mongodb

Need some help. Can't close the connection. On close the result returns as undefined

function(table, where, to_select, callback) {
    db.open(function(err, db) {
        assert.equal(null, err);
        if (!err) {
            collection = db.collection(table);
            collection.find(where, to_select).toArray(function(err, resp) { console.log(resp); //returns undefined
                callback(err,resp); 
            })
        } else {
            callback(err);
        }     
        db.close();
    });
}

You close your db too early when the query is still processing. Therefore, postpone closing the connection until your query is done and you have the results in the callback like so

function(table, where, to_select, callback) {
    db.open(function(err, db) {
        assert.equal(null, err);
        if (!err) {
            collection = db.collection(table);
            collection.find(where, to_select).toArray(function(err, resp) { console.log(resp); //returns undefined
                db.close();                    
                callback(err,resp);     
            })
        } else {
            callback(err);
            db.close();
        }     
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM