这个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操作mongodb数据库封装DB类的更多相关文章

  1. nodejs mongodb 数据库封装DB类 -转

    使用到了nodejs的插件mongoose,用mongoose操作mongodb其实蛮方便的. 关于mongoose的安装就是 npm install -g mongoose 这个DB类的数据库配置是 ...

  2. koa 基础(二十一)nodejs 操作mongodb数据库 --- 查询数据

    1.app.js /** * nodejs 操作mongodb数据库 * 1.安装 操作mongodb * cnpm install mongodb --save * 2.引入 mongodb 下面的 ...

  3. koa 基础(二十)nodejs 操作mongodb数据库 --- 新增数据

    1.app.js /** * nodejs 操作mongodb数据库 * 1.安装 操作mongodb * cnpm install mongodb --save * 2.引入 mongodb 下面的 ...

  4. NodeJS操作MongoDB数据库

    一.node.js对于mongodb的基本操作 1.数据库的开机 首先我们要先对数据库进行开机的操作,建立一个文件夹用于存放数据库文档.如D:\mongo,接下去在cmd当中键入命令-> mon ...

  5. 二十六、Nodejs 操作 MongoDb 数据库

    一. 在 Nodejs 中使用 Mongodb 前面的课程我们讲了用命令操作 MongoDB,这里我们看下如何用 nodejs 来操作数据库需要引包: npm install mongodb --sa ...

  6. nodejs 操作 mongodb 数据库

    操作手册: npmjs.com 搜索: mongodb 使用官方的  mongodb 包来操作  https://github.com/mongodb/node-mongodb-native      ...

  7. Nodejs操作MongoDB数据库示例

    //mongodb_demo.js /** cnpm install mongodb */ var MongoClient = require('mongodb').MongoClient; var ...

  8. nodejs操作monggodb数据库封装

    var MongoClient=require('mongodb').MongoClient; var DbUrl='mongodb://localhost:27017/productmanage'; ...

  9. Koa 操作 Mongodb 数据库

    node-mongodb-native的介绍 使用基于官方的 node-mongodb-native 驱动,封装一个更小.更快.更灵活的 DB 模块, 让我们用 nodejs 操作 Mongodb 数 ...

随机推荐

  1. 使用node+vue.js实现SPA应用,nodevue.jsspa应用

    使用node+vue.js实现SPA应用,nodevue.jsspa应用 http://www.bkjia.com/Javascript/1097617.html https://github.com ...

  2. 打开android虚拟机时出现a repairable android virtual device

    打开android虚拟机时出现a repairable android virtual device,虚拟机可以打开但是一直处于开机状态,具体解决方案如下: 解决方案1:换个版本,不要选 CPU/AB ...

  3. 【踩坑经历】一次Asp.NET小网站部署踩坑和解决经历

    2013年给1个大学的小客户部署过一个小型的Asp.NET网站,非常小,用的sqlite数据库,今年人家说要换台服务器,要重新部署一下,好吧,虽然早就过了服务时间,但无奈谁叫人家是客户了,二话不说,上 ...

  4. Java多线程系列--“JUC集合”09之 LinkedBlockingDeque

    概要 本章介绍JUC包中的LinkedBlockingDeque.内容包括:LinkedBlockingDeque介绍LinkedBlockingDeque原理和数据结构LinkedBlockingD ...

  5. [Qt5] Develop openCV3 by QML on Qt-creator

    QML的酷炫控件,适合移动设备开发. qt-creator的跨平台是QML与opencv的粘合剂. 关键: QImage有若干种格式,转化为相应的Mat. Mat处理完后,还要正确得还原为原来格式的Q ...

  6. spring源码分析之spring-core-io

    1. 看一下源码整体结构: 抓住主要点Resource.ResourceLoader和ResourceEditor 其中Resource作用 Interface for a resource desc ...

  7. 可视化工具gephi源码探秘(二)---导入netbeans

    在上篇<可视化工具gephi源码探秘(一)>中主要介绍了如何将gephi的源码导入myeclipse中遇到的一些问题,此篇接着上篇而来,主要讲解当下通过myeclipse导入gephi源码 ...

  8. Twitter Bootstrap 3.0 正式发布,更好地支持移动端开发

    Twitter Bootstrap 3.0 终于正式发布了.这是一个圆滑的,直观的和强大的移动优先的前端框架,用于更快,更容易的 Web 开发.几乎一切都已经被重新设计和重建,更好的支持移动端设备. ...

  9. 【AngularJS】—— 12 独立作用域

    前面通过视频学习了解了指令的概念,这里学习一下指令中的作用域的相关内容. 通过独立作用域的不同绑定,可以实现更具适应性的自定义标签.借由不同的绑定规则绑定属性,从而定义出符合更多应用场景的标签. 本篇 ...

  10. AsyncTask和Handler对比(转)

    1 ) AsyncTask实现的原理,和适用的优缺点 AsyncTask,是android提供的轻量级的异步类,可以直接继承AsyncTask,在类中实现异步操作,并提供接口反馈当前异步执行的程度(可 ...