mongodb 连接池

 
  
 //MyMongo.js
1 var mongodb = require ( 'mongodb' );
2
3 function MyMongo ( host , port , dbname ) {
4 this . host = host ;
5 this . port = port ;
6 this . dbname = dbname ;
7
8 this . server = new mongodb . Server ( this . host , this . port ,{ auto_reconnect : true , safe : true });
9
10 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 options
11
12 var self = this ;
13
14 this . db = undefined ;
15 this . queue = [];
16
17 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 collectionName
25 self . queue [ i ]. cb ( collection );
26 }
27 self . queue = [];
28
29 });
30 }
31 exports . MyMongo = MyMongo ;
32
33 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.js
 
   
1 var mongo = require ( './lib/MyMongo.js' ). MyMongo ;
2
3 var db = new mongo ( 'localhost' , 27017 , 'operation' );
4
5 exports = module . exports = {
6 db_name : 'operation' ,
7 db : db
8
9 };
//use.js
 
    
1 var config = require ( 'config.js' );
2
3 var db = config . db ;
4
7 //nodejs下的col集合
8 var COL = 'col' ;
9
10 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 });
15
16
17 db . query ( COL , function ( collection ) {
18 collection . find ({}, {
19 limit : 10
20 }). toArray ( function ( err , docs ) {
21 console . log ( "\nSecond:\n" , docs );
22 });
23 });


你可能感兴趣的:(个人总结)