当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 详解nodejs操作mongodb数据库封装DB类

详解nodejs操作mongodb数据库封装DB类

2018年06月06日  | 移动技术网IT编程  | 我要评论
这个db类也算是我经历了3个实际项目应用的,现分享出来,有需要的请借鉴批评。 上面的注释都挺详细的,我使用到了nodejs的插件mongoose,用mongoose操作m

这个db类也算是我经历了3个实际项目应用的,现分享出来,有需要的请借鉴批评。

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网