非常详细的文档http://mongodb.github.io/node-mongodb-native/2.2/quick-start/quick-start/

连接数据库

安装express 和 mongodb .

  1. npm install express mongodb --save

通过 MongoClient.connect(url, function(err, db) {}) API 连接

  1. 'use strict';
  2. const express = require("express"),
  3. mongoClient = require("mongodb").MongoClient;
  4. var app = express(),
  5. url = 'mongodb://localhost:27017/test';
  6. app.listen(3000, function(err) {
  7. if (err) {
  8. console.log("has error");
  9. }
  10. });
  11. app.get("/", function(req, res) {
  12. mongoClient.connect(url, function(err, db) {
  13. if (err) {
  14. console.log("数据库连接失败")
  15. }
  16. res.send("连接成功");
  17. db.close();
  18. })
  19. })

这样就连接成功了 .

用ES6 还是更棒的, 不过觉得配babel 比较麻烦.., 等到结尾的dao 层封装我会使用ES6的语法来完成

插入数据

提供了两个api,分别为 db.collection("student").insertOne() & db.collection("student").insertMany

  1. app.get("/", function(req, res) {
  2. mongoClient.connect(url, function(err, db) {
  3. if (err) {
  4. console.log("数据库连接失败")
  5. }
  6. db.collection("student").insertOne({ "name": "筱原明里", "age": "18" }, function(err, result) {
  7. if (err) {
  8. console.log(err);
  9. }
  10. res.send(result);
  11. })
  12. db.collection("student").insertMany([{ "name": "远野贵树", "age": "18" }, { "name": "澄田花苗" }], function(err, result) {
  13. if (err) {
  14. console.log(err);
  15. }
  16. res.send(result);
  17. })
  18. db.close();
  19. })
  20. })

查找和分页

通过db.collection().find() 会返回一个游标,通过游标的迭代来访问所有数据.

注意,each 迭代的过程是异步的 !

  1. app.get("/", function(req, res) {
  2. mongoClient.connect(url, function(err, db) {
  3. if (err) {
  4. console.log("数据库连接失败")
  5. }
  6. var collection = db.collection('student'),
  7. cursor = collection.find({}),
  8. result = [];
  9. cursor.each(function(err, doc) {
  10. console.log(doc)
  11. if (err) {
  12. console.log(err);
  13. }
  14. if (doc == null) {
  15. res.send(result);
  16. }else{
  17. result.push(doc);
  18. }
  19. });
  20. db.close();
  21. })
  22. })

但是通过each判断是否迭代完成并不是很好的方式,mongo给这个游标赋予一个更好的方法 toArray

  1. app.get("/", function(req, res) {
  2. mongoClient.connect(url, function(err, db) {
  3. if (err) {
  4. console.log("数据库连接失败")
  5. }
  6. var collection = db.collection('student'),
  7. cursor = collection.find({});
  8. cursor.toArray(function(err, docs) {
  9. // docs 就是所有的文档
  10. console.log(docs);
  11. })
  12. db.close();
  13. })
  14. })

这样做是取出全部的数据,下面是分页查询呢

mongoDB 的分页查询非常方便,封装的skip,limit 有点像 .net 中的 EF中的skip,take 等方法.

  1. app.get("/", function(req, res) {
  2. mongoClient.connect(url, function(err, db) {
  3. if (err) {
  4. console.log("数据库连接失败")
  5. }
  6. var collection = db.collection('student'),
  7. // 跳过5条再取5条
  8. cursor = collection.find({}).skip(10).limit(5);
  9. cursor.toArray(function(err, docs) {
  10. // docs 就是所有的文档
  11. console.log(docs);
  12. })
  13. db.close();
  14. })
  15. })

实际当然不能这么写,稍后会封装一个DAO,在里面会使用参数进行分页

修改

  1. app.get("/", function(req, res) {
  2. mongoClient.connect(url, function(err, db) {
  3. if (err) {
  4. console.log("数据库连接失败")
  5. }
  6. db.collection('student').updateOne({ name: "远野贵树" }, { $set: { age: 20, gender: "男" } }, function(err, result) {
  7. if (err) {
  8. console.log(err);
  9. } else {
  10. console.log(result);
  11. }
  12. })
  13. db.collection('student').updateMany({ name: "澄田花苗" }, { $set: { age: 20, gender: "女" } }, function(err, result) {
  14. if (err) {
  15. console.log(err);
  16. } else {
  17. res.send(result);
  18. }
  19. })
  20. db.close();
  21. })
  22. })

删除

删除同样包含两个api ,deleteMany & deleteOne.

  1. app.get("/", function(req, res) {
  2. mongoClient.connect(url, function(err, db) {
  3. if (err) {
  4. console.log("数据库连接失败")
  5. }
  6. db.collection("student").deleteOne({ 'name': '澄田花苗' }, function(err, result) {
  7. res.send(result);
  8. })
  9. db.collection("student").deleteMany({ 'name': '澄田花苗' }, function(err, result) {
  10. res.send(result);
  11. })
  12. db.close();
  13. })
  14. })

DAO 封装

每次像上面一样调用肯定是不可行的,所以需要封装一个DAO层.

mongodbdao.js

  1. /*
  2. * @Author: Administrator
  3. * @Date: 2017-03-13 17:14:40
  4. * @Last Modified by: Administrator
  5. * @Last Modified time: 2017-03-13 20:24:23
  6. */
  7. 'use strict';
  8. const mongoClient = require("mongodb").MongoClient,
  9. dburl = require("config").dburl;
  10. // 连接数据库,内部函数
  11. function _connectDB(callback) {
  12. mongoClient.connect(dburl, function(err, db) {
  13. if (err) {
  14. console.log(err);
  15. return;
  16. }
  17. callback(err, db);
  18. }
  19. })
  20. }
  21. exports.find = function(collectionName, json, pageOption, callback) {
  22. // 第 0 页,就跳过 0 条,第 1 页,跳过10条 ,取 10条
  23. // skip & limit ,如果参数为0,那么就忽略参数
  24. var skipNumber = pageOption.page * pageOption.count || 0,
  25. takeNumber = pageOption || 0,
  26. sort = pageOption.sort || {};
  27. _connectDB(function(err, db) {
  28. db.collection(collectionName).find(json).skip(skipNumber).limit(takeNumber).sort(sort) toArray(function(err, docs) {
  29. callback(err, docs);
  30. db.close();
  31. });
  32. })
  33. };
  34. exports.insertOne = function(collectionName, json, callback) {
  35. _connectDB(function(err, db) {
  36. db.insertOne(collectionName).insertOne(function(err, res) {
  37. callback(err, res);
  38. db.close();
  39. })
  40. })
  41. }
  42. exports.insertMany = function(collectionName, json, callback) {
  43. _connectDB(function(err, db) {
  44. db.insertOne(collectionName).insertMany(function(err, res) {
  45. callback(err, res);
  46. db.close();
  47. })
  48. })
  49. }
  50. exports.deteleOne = function(collectionName, json, callback) {
  51. _connectDB(function(err, db) {
  52. db.collection(collectionName).deteleOne(json, function(err, res) {
  53. callback(err, res);
  54. db.close();
  55. })
  56. })
  57. };
  58. exports.deteleMany = function(collectionName, json, callback) {
  59. _connectDB(function(err, db) {
  60. db.collection(collectionName).deteleMany(json, function(err, res) {
  61. callback(err, res);
  62. db.close();
  63. })
  64. })
  65. };
  66. exports.updateOne = function(collectionName, jsonQeury, jsonSet, callback) {
  67. _connectDB(function(err, db) {
  68. db.collection(collectionName).updateOne(jsonQeury, { $set: jsonSet }, function(err, res) {
  69. callback(err, res);
  70. db.close();
  71. })
  72. })
  73. };
  74. exports.updateMany = function(collectionName, jsonQeury, jsonSet, callback) {
  75. _connectDB(function(err, db) {
  76. db.collection(collectionName).updateMany(jsonQeury, { $set: jsonSet }, function(err, res) {
  77. callback(err, res);
  78. db.close();
  79. })
  80. })
  81. };
  82. exports.getAllCount = function(collectionName, json, callback) {
  83. _connectDB(function(err, db) {
  84. db.collection(collectionName).count(json, function(err, count) {
  85. callback(err, count);
  86. db.close();
  87. })
  88. })
  89. };

简单地完成了一个DAO 的封装,但是在项目中, 也是不会这样用的

因为有一个更强大的东西 mongooose,它就相当于 EF 之于 ADO.NET.

mongoDB & Nodejs 访问mongoDB (二)的更多相关文章

  1. mongoDB & Nodejs 访问mongoDB (一)

    最近的毕设需要用到mongoDB数据库,又把它拿出来再学一学,下盘并不是很稳,所以做一些笔记,不然又忘啦. 安装 mongoDB & mongoVUE mongoDB: https://www ...

  2. MongoDB最简单的入门教程之二 使用nodejs访问MongoDB

    在前一篇教程 MongoDB最简单的入门教程之一 环境搭建 里,我们已经完成了MongoDB的环境搭建. 在localhost:27017的服务器上,在数据库admin下面创建了一个名为person的 ...

  3. 使用nodejs 访问mongodb

    我使用了 express 框架 目录结构 db.js 文件 function connectionDB(hostname, port) { //注释地方暂时没有使用.是把官方代码照抄下来 // var ...

  4. 使用 MongoDB shell访问MongoDB

  5. NodeJS+Express+MongoDB

    一.MongoDB MongoDB是开源,高性能的NoSQL数据库:支持索引.集群.复制和故障转移.各种语言的驱动程序丰富:高伸缩性:MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言 ...

  6. MongoDB最简单的入门教程之五-通过Restful API访问MongoDB

    通过前面四篇的学习,我们已经在本地安装了一个MongoDB数据库,并且通过一个简单的Spring boot应用的单元测试,插入了几条记录到MongoDB中,并通过MongoDB Compass查看到了 ...

  7. 使用Spring访问Mongodb的方法大全——Spring Data MongoDB查询指南

    1.概述 Spring Data MongoDB 是Spring框架访问mongodb的神器,借助它可以非常方便的读写mongo库.本文介绍使用Spring Data MongoDB来访问mongod ...

  8. 使用Spring访问Mongodb的方法大全——Spring Data MongoDB

    1.概述 Spring Data MongoDB 是Spring框架访问mongodb的神器,借助它可以非常方便的读写mongo库.本文介绍使用Spring Data MongoDB来访问mongod ...

  9. nodejs学习笔记二——链接mongodb

    a.安装mongoose库用来链接mongodb数据库 安装mongodb数据库参考mongodb安装 前言(怨言) 本来是想安装mongodb库来链接mongodb的,命令行到nodejs工程目录: ...

随机推荐

  1. hadoop学习笔记--集群搭建

    注:大家常说的ssh其实就是一个免密码访问的东西,为了简化操作的,不用每次访问其他节点重新输入密码.但是要想配置如下: .在每台机器上执行 ssh-keygen -t rsa,连敲三次回车键(即设置空 ...

  2. VoiceEngine获取硬件信息

    #include "webrtc\voice_engine\include\voe_base.h" #include "webrtc\voice_engine\inclu ...

  3. JavaScript 轻松创建级联函数

    级联函数是什么? 在一行代码上,调用一个接一个的方法.这种技术在 JQuery 或者其他 JavaScript 库中是非常常见的. 代码如下: $('#myDiv').fadeOut().html(' ...

  4. jquery.validate.js之自定义表单验证规则

    <html> <head> <meta http-equiv="Content-Type" content="text/html; char ...

  5. com.atomikos.icatch.HeurHazardException: Heuristic Exception

    com.atomikos.icatch.HeurHazardException: Heuristic Exception: 删除Tomcat  bin文件夹下的spring.loglog4j.appe ...

  6. 【python基础】 Tkinter 之 几何管理器

    Tkinter支持三种几何管理器:网格管理器,包管理器,位置管理器 提示:由于每个管理器都有自己放置小构件的风格,最好不要在同一个容器中的小构件使用多个管理器.可以使用框架作为子容器以获取期望的布局. ...

  7. Kafka 0.10 Metadata的补充

    什么是Metadata? Topic/Partion与broker的映射关系:每一个Topic的每一个Partion的Leader.Follower的信息. 它存在哪里?持久化在Zookeeper中: ...

  8. ContextMenu控件引用以及不用v4包的方法

    最近想撸个APP出来玩玩,本想用Yalantis出的SideMenu,结果因为依赖问题放弃了,改用他们家的ContextMenu. 如果你用了v4包 那么问题就比较简单了,直接打开项目中app中的bu ...

  9. salesforce 零基础学习(六十五)VF页面应善于使用变量和函数(一)常用变量的使用

    我们在使用formula或者validation rules等的时候通常会接触到很多function,这些函数很便捷的解决了我们很多问题.其实很多函数也可以应用在VF页面中,VF页面有时候应该善于使用 ...

  10. iOS获取本地时间

    NSDate *currentDate = [NSDate date];//获取当前时间,日期 NSDateFormatter *dateFormatter = [[NSDateFormatter a ...