设为首页 收藏本站
查看: 938|回复: 0

[经验分享] nodejs mongodb 数据库封装DB类

[复制链接]

尚未签到

发表于 2017-12-15 20:57:55 | 显示全部楼层 |阅读模式
/**  * mongoose操作类(封装mongodb)
  */
  var fs = require('fs');
  var path = require('path');
  var mongoose = require('mongoose');
  var logger = require('pomelo-logger').getLogger('mongodb-log');
  var options = {
  db_user: "game",
  db_pwd: "12345678",
  db_host: "192.168.2.20",
  db_port: 27017,
  db_name: "dbname"
  };
  var dbURL = "mongodb://" + options.db_user + ":" + options.db_pwd + "@" + options.db_host + ":" + options.db_port + "/" + options.db_name;
  mongoose.connect(dbURL);
  mongoose.connection.on('connected', function (err) {
  if (err) logger.error('Database connection failure');
  });
  mongoose.connection.on('error', function (err) {
  logger.error('Mongoose connected error ' + err);
  });
  mongoose.connection.on('disconnected', function () {
  logger.error('Mongoose disconnected');
  });
  process.on('SIGINT', function () {
  mongoose.connection.close(function () {
  logger.info('Mongoose disconnected through app termination');
  process.exit(0);
  });
  });
  var DB = function () {
  this.mongoClient = {};
  var filename = path.join(path.dirname(__dirname).replace('app', ''), 'config/table.json');
  this.tabConf = JSON.parse(fs.readFileSync(path.normalize(filename)));
  };
  /**
  * 初始化mongoose model
  * @param table_name 表名称(集合名称)
  */
  DB.prototype.getConnection = function (table_name) {
  if (!table_name) return;
  if (!this.tabConf[table_name]) {
  logger.error('No table structure');
  return false;
  }
  var client = this.mongoClient[table_name];
  if (!client) {
  //构建用户信息表结构
  var nodeSchema = new mongoose.Schema(this.tabConf[table_name]);
  //构建model
  client = mongoose.model(table_name, nodeSchema, table_name);
  this.mongoClient[table_name] = client;
  }
  return client;
  };
  /**
  * 保存数据
  * @param table_name 表名
  * @param fields 表数据
  * @param callback 回调方法
  */
  DB.prototype.save = function (table_name, fields, callback) {
  if (!fields) {
  if (callback) callback({msg: 'Field is not allowed for null'});
  return false;
  }
  var err_num = 0;
  for (var i in fields) {
  if (!this.tabConf[table_name]) err_num ++;
  }
  if (err_num > 0) {
  if (callback) callback({msg: 'Wrong field name'});
  return false;
  }
  var node_model = this.getConnection(table_name);
  var mongooseEntity = new node_model(fields);
  mongooseEntity.save(function (err, res) {
  if (err) {
  if (callback) callback(err);
  } else {
  if (callback) callback(null, res);
  }
  });
  };
  /**
  * 更新数据
  * @param table_name 表名

  * @param conditions 更新需要的条件 {_id:>  * @param update_fields 要更新的字段 {age: 21, sex: 1}
  * @param callback 回调方法
  */
  DB.prototype.update = function (table_name, conditions, update_fields, callback) {
  if (!update_fields || !conditions) {
  if (callback) callback({msg: 'Parameter error'});
  return;
  }
  var node_model = this.getConnection(table_name);
  node_model.update(conditions, {$set: update_fields}, {multi: true, upsert: true}, function (err, res) {
  if (err) {
  if (callback) callback(err);
  } else {
  if (callback) callback(null, res);
  }
  });
  };
  /**
  * 更新数据方法(带操作符的)
  * @param table_name 数据表名

  * @param conditions 更新条件 {_id:>  * @param update_fields 更新的操作符 {$set: {id: 123}}
  * @param callback 回调方法
  */
  DB.prototype.updateData = function (table_name, conditions, update_fields, callback) {
  if (!update_fields || !conditions) {
  if (callback) callback({msg: 'Parameter error'});
  return;
  }
  var node_model = this.getConnection(table_name);
  node_model.findOneAndUpdate(conditions, update_fields, {multi: true, upsert: true}, function (err, data) {
  if (callback) callback(err, data);
  });
  };
  /**
  * 删除数据
  * @param table_name 表名

  * @param conditions 删除需要的条件 {_id:>  * @param callback 回调方法
  */
  DB.prototype.remove = function (table_name, conditions, callback) {
  var node_model = this.getConnection(table_name);
  node_model.remove(conditions, function (err, res) {
  if (err) {
  if (callback) callback(err);
  } else {
  if (callback) callback(null, res);
  }
  });
  };
  /**
  * 查询数据
  * @param table_name 表名
  * @param conditions 查询条件
  * @param fields 待返回字段
  * @param callback 回调方法
  */
  DB.prototype.find = function (table_name, conditions, fields, callback) {
  var node_model = this.getConnection(table_name);
  node_model.find(conditions, fields || null, {}, function (err, res) {
  if (err) {
  callback(err);
  } else {
  callback(null, res);
  }
  });
  };
  /**
  * 查询单条数据
  * @param table_name 表名
  * @param conditions 查询条件
  * @param callback 回调方法
  */
  DB.prototype.findOne = function (table_name, conditions, callback) {
  var node_model = this.getConnection(table_name);
  node_model.findOne(conditions, function (err, res) {
  if (err) {
  callback(err);
  } else {
  callback(null, res);
  }
  });
  };
  /**
  * 根据_id查询指定的数据
  * @param table_name 表名
  * @param _id 可以是字符串或 ObjectId 对象。
  * @param callback 回调方法
  */
  DB.prototype.findById = function (table_name, _id, callback) {
  var node_model = this.getConnection(table_name);
  node_model.findById(_id, function (err, res){
  if (err) {
  callback(err);
  } else {
  callback(null, res);
  }
  });
  };
  /**
  * 返回符合条件的文档数
  * @param table_name 表名
  * @param conditions 查询条件
  * @param callback 回调方法
  */
  DB.prototype.count = function (table_name, conditions, callback) {
  var node_model = this.getConnection(table_name);
  node_model.count(conditions, function (err, res) {
  if (err) {
  callback(err);
  } else {
  callback(null, res);
  }
  });
  };
  /**
  * 查询符合条件的文档并返回根据键分组的结果
  * @param table_name 表名
  * @param field 待返回的键值
  * @param conditions 查询条件
  * @param callback 回调方法
  */
  DB.prototype.distinct = function (table_name, field, conditions, callback) {
  var node_model = this.getConnection(table_name);
  node_model.distinct(field, conditions, function (err, res) {
  if (err) {
  callback(err);
  } else {
  callback(null, res);
  }
  });
  };
  /**
  * 连写查询
  * @param table_name 表名
  * @param conditions 查询条件 {a:1, b:2}
  * @param options 选项:{fields: "a b c", sort: {time: -1}, limit: 10}
  * @param callback 回调方法
  */
  DB.prototype.where = function (table_name, conditions, options, callback) {
  var node_model = this.getConnection(table_name);
  node_model.find(conditions)
  .select(options.fields || '')
  .sort(options.sort || {})
  .limit(options.limit || {})
  .exec(function (err, res) {
  if (err) {
  callback(err);
  } else {
  callback(null, res);
  }
  });
  };
  module.exports = new DB();

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-424502-1-1.html 上篇帖子: 使用express, create-react 下篇帖子: mongoDB数据更新与操作符
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表