2013-07-15 68 views
6

我正在使用mongodb的node-mongodb-native驅動程序編寫網站。如何在node.js中重用mongodb連接

我有一個關於如何一次打開MongoDB的連接,然後在user.js用它收集名用戶和集合名稱職位comment.js

我想在db.js打開數據庫連接,然後插入/保存數據問題用戶和帖子收集

目前的代碼,我db.js

var Db = require('mongodb').Db, 
    Connection = require('mongodb').Connection, 
    Server = require('mongodb').Server; 
module.exports = new Db(
    'blog', 
    new Server('localhost', Connection.DEFAULT_PORT, {auto_reconnect: true}) 
); 

user.js二手db.js S請按照

var mongodb = require('./db'); 

function User(user){ 
    this.name = user.name; 
    this.password = user.password; 
    this.email = user.email; 
}; 

module.exports = User; 

User.prototype.save = function(callback) {//save user information 
    //document to save in db 
    var user = { 
     name: this.name, 
     password: this.password, 
     email: this.email 
    }; 
    mongodb.close(); 
    //open mongodb database 
    mongodb.open(function(err, db){ 
    if(err){ 
     return callback(err); 
    } 
    //read users collection 
    db.collection('users', function(err, collection){ 
     if(err){ 
     mongodb.close(); 
     return callback(err); 
     } 
     //insert data into users collections 
     collection.insert(user,{safe: true}, function(err, user){ 
     mongodb.close(); 
     callback(err, user);//success return inserted user information 
     }); 
    }); 
    }); 
}; 

comment.js

var mongodb = require('./db'); 

function Comment(name, day, title, comment) { 
    this.name = name; 
    this.day = day; 
    this.title = title; 
    this.comment = comment; 
} 

module.exports = Comment; 

Comment.prototype.save = function(callback) { 
    var name = this.name, 
     day = this.day, 
     title = this.title, 
     comment = this.comment; 
    mongodb.open(function (err, db) { 
    if (err) { 
     return callback(err); 
    } 
    db.collection('posts', function (err, collection) { 
     if (err) { 
     mongodb.close(); 
     return callback(err); 
     } 
     //depend on name time and title add comment 
     collection.findAndModify({"name":name,"time.day":day,"title":title} 
     , [ ['time',-1] ] 
     , {$push:{"comments":comment}} 
     , {new: true} 
     , function (err,comment) { 
      mongodb.close(); 
      callback(null); 
     }); 
    }); 
    }); 
}; 
+0

你的問題聽起來不像一個問題。什麼沒有發生,並且請張貼確切挑戰您面對。 – moka

回答

8

您可以連接一次,然後重用它多次,只要你想:

var mongodb = require('mongodb'); 
var events = require('events'); 
var event = new events.EventEmitter(); 
var access = new mongodb.Server(host, port, { }); 
var client = null; 

new mongodb.Db('YOUR DATABASE', access, { safe: true, auto_reconnect: true }).open(function (err, c) { 
    if (!err) { 
    client = c; 
    console.log('database connected'); 
    event.emit('connect'); 
    } else { 
    console.log('database connection error', err); 
    event.emit('error'); 
    } 
}); 

exports.get = function(fn) { 
    if(client) { 
    fn(client); 
    } else { 
    event.on('connect', function() { 
     fn(client); 
    }); 
    } 
}; 

,然後再用它:

var db = require('./db'); 
var items; 
db.get(function(client) { 
    items = new mongodb.Collection(client, 'collection'); 
}); 

// then anywhere in your code 
db.get(function() { 
    // items.find({ ... 
}); 
+0

我的答案完全符合你剛纔的要求。請閱讀。 – moka

+0

您是否嘗試瞭解並應用上述答案中的想法和代碼?如果不是,請這樣做。如果是的話 - 請分享您的案例中的失敗。 – moka

+0

因爲您需要先實際連接到數據庫,然後再執行任何邏輯。 – moka

0

Accepted answ呃是3歲,它不會使用最新的節點 - mongodb本地驅動程序。我修改了@moka答案並添加了一些延遲和重試邏輯。

var MongoClient = require('mongodb').MongoClient; 
var events = require('events'); 
var event = new events.EventEmitter(); 
var database = null; 
var retries = 0; 
var delay = 300; 

setTimeout(connect,delay); 

// Use connect method to connect to the server 
function connect(){ 
    MongoClient.connect(process.env.MONGODB_URL, function(err, db) { 
     if(!err){ 
      console.log("Connected successfully to server"); 
      database = db; 
      event.emit('dbconnect'); 

     } else { 
      if(retries < 4){ 
       console.log('Retrying to connect db %s', retries++); 
       setTimeout(connect,delay); 
      } else { 
       console.log('Unable to connect db'); 
      } 
     } 
    }); 
} 


exports.get = function(fn) { 
    if(database !== null) { 
     fn(database); 
    } else { 
     event.on('dbconnect', function() { 
      fn(database); 
     }); 
    } 
};