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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值