• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号
您的位置:首页 > 程序设计 >JavaScript > 详解nodejs操作mongodb数据库封装DB类

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

作者:最美的痕迹 字体:[增加 减小] 来源:互联网 时间:2017-05-11

最美的痕迹通过本文主要向大家介绍了nodejs连接mongodb,nodejs操作mongodb,nodejs mongodb,nodejs链接mongodb,nodejs 查询mongodb等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

这个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();
</div>

这个类库使用方法如下:

//先包含进来
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.remo



 
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • 详解nodejs操作mongodb数据库封装DB类
  • 基于NodeJS+MongoDB+AngularJS+Bootstrap开发书店案例分析

相关文章

  • 2017-05-11jquery与ajax获取特殊字符实例详解
  • 2017-05-11JavaScript通过改变文字透明度实现的文字闪烁效果实例
  • 2017-05-11基于jQuery实现选项卡效果
  • 2017-05-11利用Javascript实现简单的转盘抽奖
  • 2017-05-11js/jq仿window文件夹框选操作插件
  • 2017-05-11js中数组插入、删除元素操作的方法
  • 2017-08-14jQuery获取两个元素之间的同胞元素(适用于无限分类的显示隐藏)
  • 2017-05-11javascript 删除数组元素和清空数组的简单方法
  • 2017-05-11微信小程序中form 表单提交和取值实例详解
  • 2017-05-11用Nodejs搭建服务器访问html、css、JS等静态资源文件

文章分类

  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号

最近更新的内容

    • jQuery自定义图片上传插件实例代码
    • 将鼠标焦点定位到文本框最后(代码分享)
    • 详解用webpack2.0构建vue2.0超详细精简版
    • Angular2下使用pdf插件的方法详解
    • javascript添加前置0(补零)的几种方法
    • jQuery点击头像上传并预览图片
    • Bootstrap实现提示框和弹出框效果
    • bootstrap table操作技巧分享
    • 详解nodeJS中读写文件方法的区别
    • bootstrap PrintThis打印插件使用详解

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有