//MyMongo.js1 var mongodb = require('mongodb');23 function MyMongo(host, port, dbname) {4 this.host = host;5 this.port = port;6 this.dbname = dbname;78 this.server = new mongodb.Server(this.host,this.port,{auto_reconnect: true,safe:true});910 this.db_connector = new mongodb.Db(this.dbname, this.server,{safe:true});//加上{safe:true}之后就不会提示//Please ensure that you set the default write concern for the database by setting one of the options1112 var self = this;1314 this.db = undefined;15 this.queue = [];1617 this.db_connector.open(function(err, db) {18 if( err ) {19 console.log(err);20 return;21 }22 self.db = db;23 for (var i = 0; i < self.queue.length; i++) {24 var collection = new mongodb.Collection(self.db, self.queue[i].cn);//cn collectionName25 self.queue[i].cb(collection);26 }27 self.queue = [];2829 });30 }31 exports.MyMongo = MyMongo;3233 MyMongo.prototype.query = function(collectionName, callback) {34 if (this.db != undefined) {35 var collection = new mongodb.Collection(this.db, collectionName);36 callback(collection);37 return;38 }39 this.queue.push({ "cn" : collectionName, "cb" : callback});40 }//config.js1 var mongo = require('./lib/MyMongo.js').MyMongo;23 var db = new mongo('localhost',27017,'operation');45 exports = module.exports = {6 db_name:'operation',7 db:db89 };//use.js1 var config = require('config.js');23 var db = config.db;47 //nodejs下的col集合8 var COL = 'col';910 db.query(COL, function(collection) {11 collection.insert({a:1,b:2,c:3},function(err, docs) {12 console.log("First:\n", docs);13 });14 });151617 db.query(COL, function(collection) {18 collection.find({}, {19 limit: 1020 }).toArray(function(err, docs) {21 console.log("\nSecond:\n", docs);22 });23 });
mongodb 连接池
最新推荐文章于 2023-08-08 10:00:00 发布