2017-10-16 69 views
0

我想用nodejs連接到mongodb。我想連接到一次MongoDB並使用需要的實例。使用nodejs的MongoClient連接

connection.js文件

var MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server; 
var mongoClient = new MongoClient(new Server('localhost', 27017)); 

module.export = mongoClient; 

我要訪問其他文件MongoClient對象執行類似操作分貝:

router.js文件

var mongoClient = require('./connection.js') 
mongoClient.open(function(err, mongoClient) { 
    var db1 = mongoClient.db("mydb"); 
    db1.collection('Persons', function (err, collection) { 

    collection.find().toArray(function(err, items) { 
     if(err) throw err;  
     console.log(items);    
    }); 

    mongoClient.close(); 
    }); 

我我得到以下錯誤:

TypeError: mongoClient.open is not a function 

回答

-1

用於連接到MongoDB的,在你的NodeJS可以這樣做

var MongoClient = require('mongodb').MongoClient, 
 
    async = require('async'), 
 
    datastore = {}; 
 

 
function connect() { 
 
    return new Promise(function(resolve, reject) { 
 
    MongoClient.connect('mongodb://host:port/dbname', function(err, db) { 
 
     if (err) 
 
     return reject(err); 
 
     // Create required collections and set indexes 
 
     async.eachLimit(collections, 1, function(collection, cb) { 
 
     db.collection(collection).createIndex(indexes, function(error) { 
 
      if (error) 
 
      return cb(error); 
 
      return cb(); 
 
     }) 
 
     }, function(error) { 
 
     if (error) { 
 
      console.error('Error creating indexes on Mongodb:', error.message); 
 
      return reject(error); 
 
     } 
 
     // export db 
 
     datastore = db; 
 
     return resolve(datastore); 
 
     }); 
 
    }); 
 
    }); 
 
} 
 

 
connect().then(function(connectionObj) { 
 
    // use connectionObj to do DB operations 
 
}).catch(function(error) { 
 
    console.error(error); 
 
})

你可以找到一個樣本@Mongodb Docs