最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解nodejs操作mongodb數(shù)據(jù)庫封裝DB類

 更新時(shí)間:2017年04月10日 10:43:49   作者:最美的痕跡  
這篇文章主要介紹了詳解nodejs操作mongodb數(shù)據(jù)庫封裝DB類,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

這個(gè)DB類也算是我經(jīng)歷了3個(gè)實(shí)際項(xiàng)目應(yīng)用的,現(xiàn)分享出來,有需要的請(qǐng)借鑒批評(píng)。

上面的注釋都挺詳細(xì)的,我使用到了nodejs的插件mongoose,用mongoose操作mongodb其實(shí)蠻方便的。

關(guān)于mongoose的安裝就是 npm install -g mongoose

這個(gè)DB類的數(shù)據(jù)庫配置是基于auth認(rèn)證的,如果您的數(shù)據(jù)庫沒有賬號(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);
    }
  });
};

/**
 * 連寫查詢
 * @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è)類庫使用方法如下:

//先包含進(jìn)來
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ù)庫集合的配置項(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í)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • npm錯(cuò)誤errno?-4048解決辦法

    npm錯(cuò)誤errno?-4048解決辦法

    這篇文章主要給大家介紹了關(guān)于npm錯(cuò)誤errno?-4048解決的相關(guān)資料,這個(gè)錯(cuò)誤代碼通常表示文件系統(tǒng)錯(cuò)誤或者硬件故障引起的問題,文中通過圖文將解決的辦法介紹的非常詳細(xì),需要的朋友可以參考下
    2023-07-07
  • Node.js服務(wù)器開啟Gzip壓縮教程

    Node.js服務(wù)器開啟Gzip壓縮教程

    開啟網(wǎng)站的 gzip 壓縮功能,通常可以高達(dá)70%,也就是說,如果你的網(wǎng)頁有30K,壓縮之后就變成9K, 對(duì)于大部分網(wǎng)站,顯然可以明顯提高瀏覽速度(注:需要瀏覽器支持)。
    2017-08-08
  • 使用Node.js腳本自動(dòng)統(tǒng)計(jì)代碼量的實(shí)現(xiàn)代碼

    使用Node.js腳本自動(dòng)統(tǒng)計(jì)代碼量的實(shí)現(xiàn)代碼

    手動(dòng)統(tǒng)計(jì)代碼行數(shù)通常會(huì)耗費(fèi)大量時(shí)間和精力,為了提高統(tǒng)計(jì)效率并減少人為錯(cuò)誤,我們可以借助自動(dòng)化工具來完成這項(xiàng)任務(wù),本文將介紹如何使用 Node.js 腳本來自動(dòng)化統(tǒng)計(jì)項(xiàng)目代碼行數(shù),讓我們能夠輕松快捷地獲取項(xiàng)目的代碼量信息,需要的朋友可以參考下
    2023-12-12
  • Node.js制作簡(jiǎn)單聊天室

    Node.js制作簡(jiǎn)單聊天室

    這篇文章主要為大家詳細(xì)介紹了Node.js制作簡(jiǎn)單聊天室的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-01-01
  • 詳解nodejs實(shí)現(xiàn)本地上傳圖片并預(yù)覽功能(express4.0+)

    詳解nodejs實(shí)現(xiàn)本地上傳圖片并預(yù)覽功能(express4.0+)

    本篇文章主要介紹了nodejs實(shí)現(xiàn)本地上傳圖片并預(yù)覽功能(express4.0+) ,具有一定的參考價(jià)值,有興趣的可以了解一下
    2017-06-06
  • nodejs基礎(chǔ)之多進(jìn)程實(shí)例詳解

    nodejs基礎(chǔ)之多進(jìn)程實(shí)例詳解

    這篇文章主要介紹了nodejs基礎(chǔ)之多進(jìn)程,結(jié)合實(shí)例形式分析了nodejs多進(jìn)程的概念、原理、相關(guān)函數(shù)使用方法及操作注意事項(xiàng),需要的朋友可以參考下
    2018-12-12
  • 使用nodejs連接mySQL寫接口全過程(增刪改查)

    使用nodejs連接mySQL寫接口全過程(增刪改查)

    這篇文章主要給大家介紹了關(guān)于使用nodejs連接mySQL寫接口(增刪改查)的相關(guān)資料,MySQL是一種常用的關(guān)系型數(shù)據(jù)庫,它與Node.js的結(jié)合可以提供強(qiáng)大的數(shù)據(jù)存儲(chǔ)和檢索功能,需要的朋友可以參考下
    2023-12-12
  • Node.js使用express寫接口的具體代碼

    Node.js使用express寫接口的具體代碼

    這篇文章主要介紹了Node.js使用express寫接口,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-03-03
  • 詳解node-ccap模塊生成captcha驗(yàn)證碼

    詳解node-ccap模塊生成captcha驗(yàn)證碼

    本篇文章主要介紹了node-ccap模塊生成captcha驗(yàn)證碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-07-07
  • node.js中RPC(遠(yuǎn)程過程調(diào)用)的實(shí)現(xiàn)原理介紹

    node.js中RPC(遠(yuǎn)程過程調(diào)用)的實(shí)現(xiàn)原理介紹

    這篇文章主要介紹了node.js中RPC(遠(yuǎn)程過程調(diào)用)的實(shí)現(xiàn)原理介紹,本文基于一個(gè)簡(jiǎn)單的RPC庫nodejs light_rpc實(shí)現(xiàn),需要的朋友可以參考下
    2014-12-12

最新評(píng)論

罗田县| 重庆市| 沈阳市| 清水县| 永靖县| 云林县| 永靖县| 阳谷县| 翼城县| 叶城县| 寿光市| 杂多县| 祥云县| 固阳县| 额尔古纳市| 林甸县| 来宾市| 淳化县| 喀喇沁旗| 城口县| 延庆县| 莒南县| 海口市| 安图县| 永吉县| 宁津县| 宣恩县| 汉川市| 曲阜市| 丹阳市| 铁岭县| 嘉峪关市| 海晏县| 桂林市| 乐至县| 威远县| 洛宁县| 定远县| 清水县| 寿光市| 米脂县|