nodejs mongodb 数据库封装DB类 -转
使用到了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();
mongoose操作类(封装mongodb)
这个类库使用方法如下:
//先包含进来
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"
}
}
nodejs mongodb 数据库封装DB类 -转的更多相关文章
- nodejs操作mongodb数据库封装DB类
这个DB类也算是我经历了3个实际项目应用的,现分享出来,有需要的请借鉴批评. 上面的注释都挺详细的,我使用到了nodejs的插件mongoose,用mongoose操作mongodb其实蛮方便的. 关 ...
- 封装DB类
封装DB类 一般一个类单独书写在一个Php文件中,为了见名知意,会对文件名有一个规范:类名.class.php 第1步: 创建DB类 第2 步: 属性设计 第3步: 初 ...
- node.js连接MongoDB数据库,db.collection is not a function完美解决
解决方法一. mongodb数据库版本回退: 这个错误是出在mongodb的库中,在nodejs里的写法和命令行中的写法不一样,3.0的api已经更新和以前的版本不不一样,我们在npm中没指定版本号的 ...
- Discuz!数据库操作DB类和C::t类介绍
类定义文件 DB类: 文件\source\class\class_core.php class DB extends discuz_database {} discuz_database类定义 文件\ ...
- tp5数据库操作 Db类
一.链接数据库 1.配置文件定义 application\database.php 注意:数据表前缀更改,在文件的prefix选项 2.类定义 二.数据库的基本使用 namespace app\de ...
- 封装类似thinkphp连贯操作数据库的Db类(简单版)。
<?php header("Content-Type:text/html;charset=utf-8"); /** *php操作mysql的工具类 */ class Db{ ...
- laravel 数据库之DB类
// 取回数据表的第一条数据 DB::table('table')->where('key', 'value')->first(); DB::table('table')->firs ...
- NodeJS连接MongoDB数据库时报错
今天第一次尝试连接MongoDB数据库,具体步骤也很简单. 首先,通过NodeJS运行环境安装MongoDB包,进入要安装的目录,执行语句 npm install mongodb 安装成功后,通过如下 ...
- 适用于app.config与web.config的ConfigUtil读写工具类 基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类) 基于ASP.NET WEB API实现分布式数据访问中间层(提供对数据库的CRUD) C# 实现AOP 的几种常见方式
适用于app.config与web.config的ConfigUtil读写工具类 之前文章:<两种读写配置文件的方案(app.config与web.config通用)>,现在重新整理一 ...
随机推荐
- table-layout 显示规则以及其他一些零碎的东西
首先对中文显示的不够好 对中文失效 auto是表格的宽和高都会随着内容增多而改变 而fixed只会增加表格的高度 宽度不会发生改变 table中的td的宽,高会根据内容的多少而变化: fix ...
- Android Studio 解析json文件出现中文乱码解决方法
作为一个Android开发初学者,好不容易找到解决方法,跟大家分享一下, 其实很简单,只要保持服务器上的文件(date2.json)与软件的编码方式一样就行. 我用的Android Studio是ut ...
- Liunx ls命令
ls命令是linux下最常用的命令.ls命令就是list的缩写缺省下ls用来打印出当前目录的清单如果ls指定其他目录那么就会显示指定目录里的文件及文件夹清单. 通过ls 命令不仅可以查看linu ...
- nginx日志
相关知识可参考文章:nginx日志格式及自定义日志配置 1.查看nginx的log配置 1)vim /etc/nginx/nginx.conf 打开为 user nginx;worker_proces ...
- springmvc+mybatis 构建cms+UC浏览器文章功能
最近公司在模拟UC浏览器做一个简单的cms系统,主要针对于企业内部的文章浏览需求,这边考虑用户大多用mobile浏览文章内容,故使用原生的ios和android进行开发,后面也会集成html5. 1. ...
- 超详细的PS抠图方法
步骤: 1.打开图片,根据图片的特点选择抠图工具: 2.在图像上找到第一个定点,要求定点要完全暴露在画布中,并且是清晰可见的顶点: 3.抠取图像时,多边形套索的定点以及边线应该向内1-2个像素,为了避 ...
- JWT-Token登陆校验
JWT:就是靠给客户端(浏览器)一个规范凭证(签名),然后服务器解析签名,代替原有的session存值. 不带refreshToken的JWT例子:https://blog.csdn.net/u011 ...
- Java 学习之集合类(Collections)
Collection(集合类) 我们是使用数组来保存数据,但是他的长度一旦创建,就已经确定了,当我们要动态传入穿值,数组就有些局限了,集合类就孕育而生:所谓集合,就是来保存,盛装数据,也可称为容器类: ...
- flex布局中的主轴和侧轴的确定
1.主轴和侧轴是通过flex-direction确定的 如果flex-direction是row或者row-reverse,那么主轴就是justify-contain 如果flex-direction ...
- Codeforces Round #517 (Div. 2, based on Technocup 2019 Elimination Round 2) D. Minimum path(字典序)
https://codeforces.com/contest/1072/problem/D 题意 给你一个n*n充满小写字母的矩阵,你可以更改任意k个格子的字符,然后输出字典序最小的从[1,1]到[n ...