nodeJS连接MongoDB的方法

分别使用Client对象和字符串连接

使用Client对象:

即使用MongoDB的MongoClient类

该对象接受两个参数:MongoClient(Server,options)

其中Server对象定义了MongoDB驱动程序应该怎样连接到服务器,包含诸如所使用的主机、端口、池的大小,

options : 数据库连接选项

以下实例:

 1 var MongoClient=require('mongodb').MongoClient,  
 2     Server=require('mongodb').Server;
 3 var client=new MongoClient(new Server('localhost',28008,{
 4                             socketOptions:{connectTimeoutMS:500},
 5                             poolSize:5,
 6                             auto_reconnect:true
 7                         },{
 8                             numberOfRetries:3,
 9                             retryMiliSeconds:500
10                         }));
11 
12 client.open(function(err,client){
13     if (err) {
14         console.log('Connection Failed');
15     }else{
16         var db=client.db("testDB");
17         if (db) {
18             console.log('conncetion success by Object of Client');
19             client.close();
20             console.log("db has closed");
21         }
22     }
23 });

使用字符串方法:

通过使用MongoClient类的connect()方法

使用语法:

MongoClient.connect(connString,options,callback)

connString语法如下:

mongodb://username:password@host:port/datebase?options

options : 数据库连接选项

以下是实例:

var MongoClient=require('mongodb').MongoClient,
    Server=require('mongodb').Server;

MongoClient.connect("mongodb://localhost:28008/foobar",{
    db:{w:1,native_parser:false},
    server:{
        poolSize:5,
        socketOptions:{connectTimeoutMS:500},
        auto_reconnect:true
    },
    replSet:{},
    mongos:{}
    },function(err,db){
        if (err) {
            console.log("connect failed");
        }else{
            console.log("conenct success by string of mongodb");
            db.logout(function(err,result){
                if (!err) {
                    console.log('logged out success');
                }
                db.close();
                console.log('connect close');
            })
        }
    });
原文地址:https://www.cnblogs.com/Bideam/p/5760051.html