2013-03-18 20 views
1

在我的應用程序中使用node.js和mongoDB.Below是我的示例代碼。如何使mongoDB實例可用node.js中的所有其他模塊

var mongodb = require('mongodb'); 
var server = new mongodb.Server("localhost", 27017, {}); 

new mongodb.Db('test', server, {w: 1}).open(function (error, client) { 
    if (error) throw error; 
    var collection = new mongodb.Collection(client, 'test_collection'); 
    collection.insert({hello: 'world'}, {safe:true}, 
    function(err, objects) { 
     if(!err){ 
      console.log('Data inserted successfully.'); 
     } 
     if (err && err.message.indexOf('E11000 ') !== -1) { 
      // this _id was already inserted in the database 
     } 
    }); 
}); 

現在我需要在我的應用程序中的其他模塊mongoDB實例。我可以這樣做。

+1

請格式化你的代碼。我這次爲你做了,但如果它被格式化了,它會更容易閱讀。 – tjameson 2013-03-18 06:32:06

+0

@tjameson好的謝謝。以後我會自己做 – sachin 2013-03-18 06:38:28

回答

0

一種簡單的方法,如果我們假設您發佈的代碼是在app.js你可以重寫第2行:

var server = exports.db = new mongodb.Server("localhost", 27017, {}); 

而且在需要的情況下訪問模塊簡單地寫:

require('app').db 

更常見的方式可能是將共享的東西放在settings.js文件中,或者擁有專用的數據庫接口模塊。

更新

要訪問打開的客戶你會以同樣的方式暴露在客戶端:

new mongodb.Db('test', server, {w: 1}).open(function (error, client) { 
    exports.client = client; 
    // ... 
}); 
+0

我需要mongoDB打開函數中提到的客戶端對象。我不想在每個模塊中重複打開連接。 – sachin 2013-03-18 08:31:22

+0

更新了一個例子。但是,如果你想要更多的抽象,我建議你看看像貓鼬。 – 2013-03-18 08:40:50

+0

好的謝謝................ – sachin 2013-03-18 08:43:01

相關問題