详解nodejs操作mongodb数据库封装DB类


Posted in NodeJs onApril 10, 2017

这个DB类也算是我经历了3个实际项目应用的,现分享出来,有需要的请借鉴批评。

上面的注释都挺详细的,我使用到了nodejs的插件mongoose,用mongoose操作mongodb其实蛮方便的。

关于mongoose的安装就是 npm install -g mongoose

这个DB类的数据库配置是基于auth认证的,如果您的数据库没有账号与密码则留空即可。

/**
 * 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][i]) 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: id, user_name: name}
 * @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: id, user_name: name}
 * @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: 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();

这个类库使用方法如下:

//先包含进来
var MongoDB = require('./mongodb');

//查询一条数据
MongoDB.findOne('user_info', {_id: user_id}, function (err, res) {
  console.log(res);
});

//查询多条数据
MongoDB.find('user_info', {type: 1}, {}, function (err, res) {
  console.log(res);
});

//更新数据并返回结果集合
MongoDB.updateData('user_info', {_id: user_info._id}, {$set: update_data}, function(err, user_info) {
   callback(null, user_info);
});

//删除数据
MongoDB.remove('user_data', {user_id: 1});

就先举这些例子,更多的可亲自尝试吧!

其中配置中的 config/table.json 是数据库集合的配置项,结构如下:

{
"user_stats_data": {
    "user_id": "Number",
    "platform": "Number",
    "user_first_time": "Number",
    "create_time": "Number"
  },
  "room_data": {
    "room_id": "String",
    "room_type": "Number",
    "user_id": "Number",
    "player_num": "Number",
    "diamond_num": "Number",
    "normal_settle": "Number",
    "single_settle": "Number",
    "create_time": "Number"
  },
  "online_data": {
    "server_id": "String",
    "pf": "Number",
    "player_num": "Number",
    "room_list": "String",
    "update_time": "Number"
  }
}

记得每次给添加字段时,要往这个table.json里面添加。由于nodejs这个服务器的改动,更改table.json往往需要重启游戏服务的。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

NodeJs 相关文章推荐
windows下安装nodejs及框架express
Aug 07 NodeJs
Nodejs进阶:基于express+multer的文件上传实例
Nov 21 NodeJs
详解nodejs实现本地上传图片并预览功能(express4.0+)
Jun 28 NodeJs
nodejs后台集成ueditor富文本编辑器的实例
Jul 11 NodeJs
深入学习nodejs中的async模块的使用方法
Jul 12 NodeJs
Nodejs中使用phantom将html转为pdf或图片格式的方法
Sep 18 NodeJs
nodejs实现的简单web服务器功能示例
Mar 15 NodeJs
CentOS7中源码编译安装NodeJS的完整步骤
Oct 13 NodeJs
nodejs异步编程基础之回调函数用法分析
Dec 26 NodeJs
nodejs分离html文件里面的js和css的方法
Apr 09 NodeJs
详解nodejs微信公众号开发——3.封装消息响应模块
Apr 10 #NodeJs
详解nodejs微信公众号开发——2.自动回复
Apr 10 #NodeJs
详解nodejs微信公众号开发——1.接入微信公众号
Apr 10 #NodeJs
使用 NodeJS+Express 开发服务端的简单介绍
Apr 07 #NodeJs
初识NodeJS服务端开发入门(Express+MySQL)
Apr 07 #NodeJs
nodejs服务搭建教程 nodejs访问本地站点文件
Apr 07 #NodeJs
nodejs爬虫遇到的乱码问题汇总
Apr 07 #NodeJs
You might like
php HtmlReplace输入过滤安全函数
2010/07/03 PHP
一个简单php扩展介绍与开发教程
2010/08/19 PHP
php中去除所有js,html,css代码
2010/10/12 PHP
PHP+Ajax检测用户名或邮件注册时是否已经存在实例教程
2014/08/23 PHP
PHP new static 和 new self详解
2017/02/19 PHP
BOOM vs RR BO3 第一场2.13
2021/03/10 DOTA
SeaJS 与 RequireJS 的差异对比
2014/12/08 Javascript
webpack+vue.js实现组件化详解
2016/10/12 Javascript
Angular企业级开发——MVC之控制器详解
2017/02/20 Javascript
ajax前台后台跨域请求处理方式
2018/02/08 Javascript
快速解决bootstrap下拉菜单无法隐藏的问题
2018/08/10 Javascript
微信小程序支付PHP代码
2018/08/23 Javascript
Vuex的各个模块封装的实现
2020/06/05 Javascript
[01:22:28]DOTA2-DPC中国联赛 正赛 SAG vs RNG BO3 第一场 1月18日
2021/03/11 DOTA
基于python select.select模块通信的实例讲解
2017/09/21 Python
Python批量更改文件名的实现方法
2017/10/29 Python
无法使用pip命令安装python第三方库的原因及解决方法
2018/06/12 Python
Python数据类型之Dict字典实例详解
2019/05/07 Python
python GUI库图形界面开发之PyQt5 Qt Designer工具(Qt设计师)详细使用方法及Designer ui文件转py文件方法
2020/02/26 Python
Python self用法详解
2020/11/28 Python
css3实现3d旋转动画特效
2015/03/10 HTML / CSS
英语专业毕业生自我鉴定
2013/11/09 职场文书
教育英语专业毕业生的求职信
2014/03/13 职场文书
警校毕业生自我评价
2014/04/06 职场文书
公司向个人借款协议书范本
2014/10/09 职场文书
2014年超市员工工作总结
2014/11/18 职场文书
欠款纠纷起诉状
2015/05/19 职场文书
2015初中政治教学工作总结
2015/07/21 职场文书
开学典礼致辞
2015/07/29 职场文书
幼儿教师继续教育培训心得体会
2016/01/19 职场文书
《月球之谜》教学反思
2016/02/20 职场文书
2019最新婚庆对联集锦!
2019/07/10 职场文书
Python 可迭代对象 iterable的具体使用
2021/08/07 Python
Redis命令处理过程源码解析
2022/02/12 Redis
Spring Boot 使用 Spring-Retry 进行重试框架
2022/04/24 Java/Android
Nginx使用ngx_http_upstream_module实现负载均衡功能示例
2022/08/05 Servers