目前看到的写法都是 每次curd的时候 connect一次,这样导致代码重复率太高,请问下 怎么把 如何返回一个connection? 后续的crud操作 这届用这个connection?
我写的一个简单的例子: var MongoClient = require(‘mongodb’).MongoClient var url = 'mongodb://localhost:27017’; function mongoDB(url){ this.url = url; } var dbList = function(db, callbacck, errback){ var admin = db.admin(); admin.listDatabases(function(err, dbs){ if(err){ errback(err); }else callbacck(dbs); }); }
mongoDB.prototype.getDBList = function(){ MongoClient.connect(this.url, function(err, db){ dbList(db, function(data){ db.close(); }) }) }
var mongo = new mongoDB(url);
mongo.getDBList();
简化了一下: var MongoClient = require(‘mongodb’).MongoClient
var url = 'mongodb://localhost:27017’;
function mongoDB(url){ this.url = url; }
var getConnection = function(url, callback, errback){ MongoClient.connect(url, function(err, db){ callback(db); }) }
mongoDB.prototype.getDBList = function(callback){ console.log(this.url) getConnection(url, function(db){ var admin = db.admin(); admin.listDatabases(function(err, dbs){ console.log(dbs); db.close(); }); }); }
var mongo = new mongoDB(url);
mongo.getDBList();
// module.exports = mongoDB;