Wie man die Mongodb-Verbindung in node.js wiederverwendet

Ich benutze Node-Mongodb-native Treiber mit Mongodb, um eine Website zu schreiben.

Ich habe eine Frage, wie man eine Mongodb-Verbindung einmal öffnet und sie dann in Sammlungsnamenbenutzern in verwendetuser.js und Sammlungsname Beiträge incomment.js

Ich möchte die Datenbankverbindung in öffnendb.js dann zum Einfügen / Speichern von Daten für Benutzer- und Postsammlungen

Derzeit Code, meindb.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})
);

ich benutztedb.js imuser.js wie folgt

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

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

Antworten auf die Frage(2)

Ihre Antwort auf die Frage