注:摘自网络

上面的注释都挺详细的,我使用到了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往往需要重启游戏服务的。

node操作mogondb数据库的封装的更多相关文章

  1. Node 操作MySql数据库

    1, 需要安装 MySQL 依赖 =>  npm i mysql -D 2, 封装一个工具类 mysql-util.js // 引入 mysql 数据库连接依赖 const mysql = re ...

  2. Node 操作 MySQL 数据库

    1, 下载 mysql 依赖 => npm -i mysql 2, 写一个核心工具类, 用于获取线程池连接 mysql-util.js // 引入 mysql 数据库连接依赖 const mys ...

  3. node操作mysql数据库

    1.建立数据库连接:createConnection(Object)方法       该方法接受一个对象作为参数,该对象有四个常用的属性host,user,password,database.与php ...

  4. node操作mongoDB数据库的最基本例子

    连接数据库 var mongo=require("mongodb"); var host="localhost"; var port=mongo.Connect ...

  5. 你不会用node 操作mysql数据库吗?

    http://static.runoob.com/download/websites.sql这是实例 websites.sql文件1.安装node的mysql服务 npm install mysql ...

  6. node操作MongoDB数据库之插入

    在上一篇中我们介绍了MongoDB的安装与配置,接下来的我们来看看在node中怎样操作MongoDB数据库. 在操作数据库之前,首先应该像关系型数据库一样建个数据库把... 启动数据库 利用命令提示符 ...

  7. Node操作MongoDB并与express结合实现图书管理系统

    Node操作MongoDB数据库 原文链接:http://www.xingxin.me/ Web应用离不开数据库的操作,我们将陆续了解Node操作MongoDB与MySQL这是两个具有代表性的数据库, ...

  8. node.js操作MySQL数据库

    MySQL数据库作为最流行的开源数据库.基本上是每个web开发者必须要掌握的数据库程序之一了. 基本使用 node.js上,最受欢迎的mysql包就是mysql模块. npm install mysq ...

  9. 使用node js 操作 Mysql 数据库

    使用node js 操作 Mysql 数据库 http://www.nodejs.org/ //node js 数据库操作 MySQL //使用https://github.com/felixge/n ...

随机推荐

  1. 偶遇bash 的while read line 的问题

    自己开发的过程中,我从数据库里读出来一个值,写入某个临时文件,再让脚本做 cat tmp.log |while read line  的时候 readline每次都是少一行, 最后发现,是换行符的问题 ...

  2. Linux网络编程函数

    1. Server端-socket/bind/listen/accept/read socket(AF_INET, SOCK_STREAM, 0); //指定端口,内核将端口上的数据转发给该socke ...

  3. C#常用控件的属性以及方法(转载)

    -----以前看别人的,保存了下来,但是忘了源处,望见谅. C#常用控件属性及方法介绍 目录 1.窗体(Form) 2.Label (标签)控件 3.TextBox(文本框)控件 4.RichText ...

  4. MVVM技术 - 的实现 @{}来进行 调用那个 DataBinding方法

    new Material Design 支持哭 还有 Data Binding 结束   使用DataBindign 结束 我们很方面的实现 MVVM设计模式   什么是MVVM model 呢.   ...

  5. hibernate课程 初探单表映射3-2 基本类型

    本节内容:(介绍基本类型) 1 数据类型 简介 2 时间类型 简介 3 时间类型 demo 1 hibernate类型 java类型   integer/int java.lang.Integer/i ...

  6. webpack实用小功能介绍

    1.overlay overlay属于devServer的属性,配置案例如下: ? 1 2 3 4 5 6 devServer: {  overlay: {   errors: true,   war ...

  7. mysql-作业

    一.表关系 请创建如下表,并创建相关约束                 班级表:class       学生表:student       cid caption grade_id   sid sn ...

  8. 从零开始的全栈工程师——js篇2.9(this详解)

    this 一.this是js的一个关键字 指定一个对象然后去替代他    只研究函数内的this 分两种 函数内的this和函数外的this1)函数内的this指向行为发生的主体2)函数外的this都 ...

  9. iis6.0 建立站点

    公司网站的服务器甚多 其中还包括早期的iis6.0 的网站服务器 由于之前没有接触过 特此记录建立站点过程和注意事项 1.每个站点最好都新建一个用户名 方便管理 这里操作系统是 winXP 现在运行界 ...

  10. 美国L1签证申请的常见问题解析

    美国L1是一种允许在美国和中国都有机构的跨国公司从国外的母公司派遣一定层次的经理或专业技术人员去美国分支机构工作的非移民签证.L1签证分两类:美国L1A是跨国公司经理及主管人员签证,L1B是专门技术人 ...