詳解nodejs操作mongodb數(shù)據(jù)庫(kù)封裝DB類
這個(gè)DB類也算是我經(jīng)歷了3個(gè)實(shí)際項(xiàng)目應(yīng)用的,現(xiàn)分享出來(lái),有需要的請(qǐng)借鑒批評(píng)。
上面的注釋都挺詳細(xì)的,我使用到了nodejs的插件mongoose,用mongoose操作mongodb其實(shí)蠻方便的。
關(guān)于mongoose的安裝就是 npm install -g mongoose
這個(gè)DB類的數(shù)據(jù)庫(kù)配置是基于auth認(rèn)證的,如果您的數(shù)據(jù)庫(kù)沒(méi)有賬號(hào)與密碼則留空即可。
/**
* 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) {
//構(gòu)建用戶信息表結(jié)構(gòu)
var nodeSchema = new mongoose.Schema(this.tabConf[table_name]);
//構(gòu)建model
client = mongoose.model(table_name, nodeSchema, table_name);
this.mongoClient[table_name] = client;
}
return client;
};
/**
* 保存數(shù)據(jù)
* @param table_name 表名
* @param fields 表數(shù)據(jù)
* @param callback 回調(diào)方法
*/
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);
}
});
};
/**
* 更新數(shù)據(jù)
* @param table_name 表名
* @param conditions 更新需要的條件 {_id: id, user_name: name}
* @param update_fields 要更新的字段 {age: 21, sex: 1}
* @param callback 回調(diào)方法
*/
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);
}
});
};
/**
* 更新數(shù)據(jù)方法(帶操作符的)
* @param table_name 數(shù)據(jù)表名
* @param conditions 更新條件 {_id: id, user_name: name}
* @param update_fields 更新的操作符 {$set: {id: 123}}
* @param callback 回調(diào)方法
*/
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);
});
};
/**
* 刪除數(shù)據(jù)
* @param table_name 表名
* @param conditions 刪除需要的條件 {_id: id}
* @param callback 回調(diào)方法
*/
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);
}
});
};
/**
* 查詢數(shù)據(jù)
* @param table_name 表名
* @param conditions 查詢條件
* @param fields 待返回字段
* @param callback 回調(diào)方法
*/
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);
}
});
};
/**
* 查詢單條數(shù)據(jù)
* @param table_name 表名
* @param conditions 查詢條件
* @param callback 回調(diào)方法
*/
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);
}
});
};
/**
* 根據(jù)_id查詢指定的數(shù)據(jù)
* @param table_name 表名
* @param _id 可以是字符串或 ObjectId 對(duì)象。
* @param callback 回調(diào)方法
*/
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);
}
});
};
/**
* 返回符合條件的文檔數(shù)
* @param table_name 表名
* @param conditions 查詢條件
* @param callback 回調(diào)方法
*/
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);
}
});
};
/**
* 查詢符合條件的文檔并返回根據(jù)鍵分組的結(jié)果
* @param table_name 表名
* @param field 待返回的鍵值
* @param conditions 查詢條件
* @param callback 回調(diào)方法
*/
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);
}
});
};
/**
* 連寫(xiě)查詢
* @param table_name 表名
* @param conditions 查詢條件 {a:1, b:2}
* @param options 選項(xiàng):{fields: "a b c", sort: {time: -1}, limit: 10}
* @param callback 回調(diào)方法
*/
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();
這個(gè)類庫(kù)使用方法如下:
//先包含進(jìn)來(lái)
var MongoDB = require('./mongodb');
//查詢一條數(shù)據(jù)
MongoDB.findOne('user_info', {_id: user_id}, function (err, res) {
console.log(res);
});
//查詢多條數(shù)據(jù)
MongoDB.find('user_info', {type: 1}, {}, function (err, res) {
console.log(res);
});
//更新數(shù)據(jù)并返回結(jié)果集合
MongoDB.updateData('user_info', {_id: user_info._id}, {$set: update_data}, function(err, user_info) {
callback(null, user_info);
});
//刪除數(shù)據(jù)
MongoDB.remove('user_data', {user_id: 1});
就先舉這些例子,更多的可親自嘗試吧!
其中配置中的 config/table.json 是數(shù)據(jù)庫(kù)集合的配置項(xiàng),結(jié)構(gòu)如下:
{
"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"
}
}
記得每次給添加字段時(shí),要往這個(gè)table.json里面添加。由于nodejs這個(gè)服務(wù)器的改動(dòng),更改table.json往往需要重啟游戲服務(wù)的。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- nodejs對(duì)mongodb數(shù)據(jù)庫(kù)的增加修刪該查實(shí)例代碼
- Nodejs實(shí)現(xiàn)的操作MongoDB數(shù)據(jù)庫(kù)功能完整示例
- nodejs實(shí)現(xiàn)連接mongodb數(shù)據(jù)庫(kù)的方法示例
- 使用Nodejs連接mongodb數(shù)據(jù)庫(kù)的實(shí)現(xiàn)代碼
- nodejs連接mongodb數(shù)據(jù)庫(kù)實(shí)現(xiàn)增刪改查
- NodeJS連接MongoDB數(shù)據(jù)庫(kù)時(shí)報(bào)錯(cuò)的快速解決方法
- NodeJs Express框架操作MongoDB數(shù)據(jù)庫(kù)執(zhí)行方法講解
相關(guān)文章
nodejs調(diào)用cmd命令實(shí)現(xiàn)復(fù)制目錄
本文給大家介紹的是如何在nodejs中調(diào)用CMD命令,從而實(shí)現(xiàn)目錄的復(fù)制,非常的實(shí)用,有需要的小伙伴可以參考下。2015-05-05
微信小程序搭載node.js服務(wù)器的簡(jiǎn)單教程
小程序是一種全新的連接用戶與服務(wù)的方式,它可以在微信內(nèi)被便捷地獲取和傳播,同時(shí)具有出色的使用體驗(yàn),下面這篇文章主要給大家介紹了關(guān)于微信小程序搭載node.js服務(wù)器的簡(jiǎn)單教程,需要的朋友可以參考下2022-12-12
node.js中的fs.fstatSync方法使用說(shuō)明
這篇文章主要介紹了node.js中的fs.fstatSync方法使用說(shuō)明,本文介紹了fs.fstatSync的方法說(shuō)明、語(yǔ)法、接收參數(shù)、使用實(shí)例和實(shí)現(xiàn)源碼,需要的朋友可以參考下2014-12-12
Windows系統(tǒng)下安裝Node.js的步驟圖文詳解
這篇文章主要給大家介紹了Windows系統(tǒng)下Node.js的安裝教程,Node.js是用于后端編程的JavaScript框架,文中給出了詳細(xì)圖文介紹,有需要的朋友可以參考下,下面來(lái)一起看看吧。2016-11-11
nodejs連接mysql數(shù)據(jù)庫(kù)簡(jiǎn)單封裝示例-mysql模塊
本篇文章主要介紹了nodejs連接mysql數(shù)據(jù)庫(kù)簡(jiǎn)單封裝(mysql模塊),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-04-04
window10系統(tǒng)下nvm詳細(xì)安裝步驟以及使用
nvm可以管理不同版本的node和npm,可以簡(jiǎn)單操作node版本的切換、安裝、查看等,下面這篇文章主要給大家介紹了關(guān)于window10系統(tǒng)下nvm詳細(xì)安裝步驟以及使用的相關(guān)資料,需要的朋友可以參考下2022-07-07

