微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在node.js中重用mongodb连接

我正在使用 mongodb的node- mongodb-native驱动程序来编写一个网站.

我有一个关于如何打开mongodb连接一次的问题,然后在user.js中的集合名称用户和comment.js中的集合名称帖子中使用它

我想在db.js中打开db连接,然后为用户和帖子集合插入/保存数据

目前代码,我的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,如下所示

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},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},comment) {
          mongodb.close();
          callback(null);
      });   
    });
  });
};

解决方法

您可以连接一次,然后根据需要重复使用多次:
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({ ...
});

原文地址:https://www.jb51.cc/nodejs/241270.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐