欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解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)分享出來,有需要的請借鑒批評。

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

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

這個(gè)DB類的數(shù)據(jù)庫配置是基于auth認(rèn)證的,如果您的數(shù)據(jù)庫沒有賬號與密碼則留空即可。

/**
 * 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 對象。
 * @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ù)器的改動,更改table.json往往需要重啟游戲服務(wù)的。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Node.js使用Express.Router的方法

    Node.js使用Express.Router的方法

    這篇文章主要為大家詳細(xì)介紹了Node.js使用Express.Router的方法 ,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-11-11
  • nodejs調(diào)用cmd命令實(shí)現(xiàn)復(fù)制目錄

    nodejs調(diào)用cmd命令實(shí)現(xiàn)復(fù)制目錄

    本文給大家介紹的是如何在nodejs中調(diào)用CMD命令,從而實(shí)現(xiàn)目錄的復(fù)制,非常的實(shí)用,有需要的小伙伴可以參考下。
    2015-05-05
  • 微信小程序搭載node.js服務(wù)器的簡單教程

    微信小程序搭載node.js服務(wù)器的簡單教程

    小程序是一種全新的連接用戶與服務(wù)的方式,它可以在微信內(nèi)被便捷地獲取和傳播,同時(shí)具有出色的使用體驗(yàn),下面這篇文章主要給大家介紹了關(guān)于微信小程序搭載node.js服務(wù)器的簡單教程,需要的朋友可以參考下
    2022-12-12
  • node.js中的fs.fstatSync方法使用說明

    node.js中的fs.fstatSync方法使用說明

    這篇文章主要介紹了node.js中的fs.fstatSync方法使用說明,本文介紹了fs.fstatSync的方法說明、語法、接收參數(shù)、使用實(shí)例和實(shí)現(xiàn)源碼,需要的朋友可以參考下
    2014-12-12
  • Windows系統(tǒng)下安裝Node.js的步驟圖文詳解

    Windows系統(tǒng)下安裝Node.js的步驟圖文詳解

    這篇文章主要給大家介紹了Windows系統(tǒng)下Node.js的安裝教程,Node.js是用于后端編程的JavaScript框架,文中給出了詳細(xì)圖文介紹,有需要的朋友可以參考下,下面來一起看看吧。
    2016-11-11
  • Node.js中路徑處理模塊path詳解

    Node.js中路徑處理模塊path詳解

    相信大家都知道在nodejs中,path是個(gè)使用頻率很高,但卻讓人又愛又恨的模塊。因?yàn)椴糠治臋n說的不夠清晰,還有部分因?yàn)榻涌诘钠脚_差異性。本文就給大家詳細(xì)介紹下關(guān)于Node.js中的路徑處理模塊path,希望能對大家學(xué)習(xí)或者使用模塊path有所幫助,下面來一起看看吧。
    2016-11-11
  • nodejs連接mysql數(shù)據(jù)庫簡單封裝示例-mysql模塊

    nodejs連接mysql數(shù)據(jù)庫簡單封裝示例-mysql模塊

    本篇文章主要介紹了nodejs連接mysql數(shù)據(jù)庫簡單封裝(mysql模塊),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。
    2017-04-04
  • window10系統(tǒng)下nvm詳細(xì)安裝步驟以及使用

    window10系統(tǒng)下nvm詳細(xì)安裝步驟以及使用

    nvm可以管理不同版本的node和npm,可以簡單操作node版本的切換、安裝、查看等,下面這篇文章主要給大家介紹了關(guān)于window10系統(tǒng)下nvm詳細(xì)安裝步驟以及使用的相關(guān)資料,需要的朋友可以參考下
    2022-07-07
  • Node.js原生api搭建web服務(wù)器的方法步驟

    Node.js原生api搭建web服務(wù)器的方法步驟

    這篇文章主要介紹了Node.js原生api搭建web服務(wù)器的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-02-02
  • 深入淺析Node.js 事件循環(huán)

    深入淺析Node.js 事件循環(huán)

    Node.js 是單進(jìn)程單線程應(yīng)用程序,但是通過事件和回調(diào)支持并發(fā),所以性能非常高,本文給大家介紹nodejs事件循環(huán)相關(guān)知識,對此感興趣的朋友快來學(xué)習(xí)吧
    2015-12-12

最新評論