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

连接数据库

安装express 和 mongodb .

npm install express mongodb --save

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

'use strict';
const express = require("express"),
mongoClient = require("mongodb").MongoClient;
var app = express(),
url = 'mongodb://localhost:27017/test'; app.listen(3000, function(err) {
if (err) {
console.log("has error");
}
});
app.get("/", function(req, res) {
mongoClient.connect(url, function(err, db) {
if (err) {
console.log("数据库连接失败")
}
res.send("连接成功");
db.close();
})
})

这样就连接成功了 .

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

插入数据

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

app.get("/", function(req, res) {
mongoClient.connect(url, function(err, db) {
if (err) {
console.log("数据库连接失败")
}
db.collection("student").insertOne({ "name": "筱原明里", "age": "18" }, function(err, result) {
if (err) {
console.log(err);
}
res.send(result);
}) db.collection("student").insertMany([{ "name": "远野贵树", "age": "18" }, { "name": "澄田花苗" }], function(err, result) {
if (err) {
console.log(err);
}
res.send(result);
}) db.close();
})
})

查找和分页

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

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

app.get("/", function(req, res) {
mongoClient.connect(url, function(err, db) {
if (err) {
console.log("数据库连接失败")
}
var collection = db.collection('student'),
cursor = collection.find({}),
result = [];
cursor.each(function(err, doc) {
console.log(doc)
if (err) {
console.log(err);
}
if (doc == null) {
res.send(result);
}else{
result.push(doc);
}
});
db.close();
})
})

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

app.get("/", function(req, res) {
mongoClient.connect(url, function(err, db) {
if (err) {
console.log("数据库连接失败")
}
var collection = db.collection('student'),
cursor = collection.find({}); cursor.toArray(function(err, docs) {
// docs 就是所有的文档
console.log(docs);
})
db.close();
})
})

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

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

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

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

修改

app.get("/", function(req, res) {
mongoClient.connect(url, function(err, db) {
if (err) {
console.log("数据库连接失败")
}
db.collection('student').updateOne({ name: "远野贵树" }, { $set: { age: 20, gender: "男" } }, function(err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
}
})
db.collection('student').updateMany({ name: "澄田花苗" }, { $set: { age: 20, gender: "女" } }, function(err, result) {
if (err) {
console.log(err);
} else {
res.send(result);
}
})
db.close();
})
})

删除

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

app.get("/", function(req, res) {
mongoClient.connect(url, function(err, db) {
if (err) {
console.log("数据库连接失败")
}
db.collection("student").deleteOne({ 'name': '澄田花苗' }, function(err, result) {
res.send(result);
}) db.collection("student").deleteMany({ 'name': '澄田花苗' }, function(err, result) {
res.send(result);
})
db.close();
})
})

DAO 封装

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

mongodbdao.js

/*
* @Author: Administrator
* @Date: 2017-03-13 17:14:40
* @Last Modified by: Administrator
* @Last Modified time: 2017-03-13 20:24:23
*/ 'use strict';
const mongoClient = require("mongodb").MongoClient,
dburl = require("config").dburl; // 连接数据库,内部函数
function _connectDB(callback) {
mongoClient.connect(dburl, function(err, db) {
if (err) {
console.log(err);
return;
}
callback(err, db);
}
})
} exports.find = function(collectionName, json, pageOption, callback) {
// 第 0 页,就跳过 0 条,第 1 页,跳过10条 ,取 10条
// skip & limit ,如果参数为0,那么就忽略参数
var skipNumber = pageOption.page * pageOption.count || 0,
takeNumber = pageOption || 0,
sort = pageOption.sort || {};
_connectDB(function(err, db) {
db.collection(collectionName).find(json).skip(skipNumber).limit(takeNumber).sort(sort) toArray(function(err, docs) {
callback(err, docs);
db.close();
});
})
}; exports.insertOne = function(collectionName, json, callback) {
_connectDB(function(err, db) {
db.insertOne(collectionName).insertOne(function(err, res) {
callback(err, res);
db.close();
})
})
}
exports.insertMany = function(collectionName, json, callback) {
_connectDB(function(err, db) {
db.insertOne(collectionName).insertMany(function(err, res) {
callback(err, res);
db.close();
})
})
} exports.deteleOne = function(collectionName, json, callback) {
_connectDB(function(err, db) {
db.collection(collectionName).deteleOne(json, function(err, res) {
callback(err, res);
db.close();
})
})
}; exports.deteleMany = function(collectionName, json, callback) {
_connectDB(function(err, db) {
db.collection(collectionName).deteleMany(json, function(err, res) {
callback(err, res);
db.close();
})
})
}; exports.updateOne = function(collectionName, jsonQeury, jsonSet, callback) {
_connectDB(function(err, db) {
db.collection(collectionName).updateOne(jsonQeury, { $set: jsonSet }, function(err, res) {
callback(err, res);
db.close();
})
})
}; exports.updateMany = function(collectionName, jsonQeury, jsonSet, callback) {
_connectDB(function(err, db) {
db.collection(collectionName).updateMany(jsonQeury, { $set: jsonSet }, function(err, res) {
callback(err, res);
db.close();
})
})
};
exports.getAllCount = function(collectionName, json, callback) {
_connectDB(function(err, db) {
db.collection(collectionName).count(json, function(err, count) {
callback(err, count);
db.close();
})
})
};

简单地完成了一个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. CFD-post的奇技淫巧

    此处记录两个后处理美化的技巧:1.关于contour显示的美化:2.关于legend的显示美化 1. 直接举例说明,现在cfd-post里导入了一个二维case,先建立一个plane: apply以后 ...

  2. cvc-complex-type.2.4.c: The matching wildcard...

    在家里的电脑好好的,在单位的就不行,需要把web app libraties提到 最前面,然后clean一下项目

  3. Node.js理解

    JavaScript单线程的误解 在我接触JavaScript(无论浏览器还是NodeJS)的时间里,总是遇到有朋友有多线程的需求.而在NodeJS方面,有朋友甚至直接说到,NodeJS是单线程的,无 ...

  4. 如何解决“BPM导入组织架构出现问题导致系统无法登陆”

    遇到问题如图所示↓ 进入H3系统登陆页面. 点击登陆后显示如图错误. 跟踪后显示参数为空.问题描述:通过web service方式进行组织机构导入,只导入ObjectID和Name等共通的6个字段.导 ...

  5. python yield generator 详解

    本文将由浅入深详细介绍yield以及generator,包括以下内容:什么generator,生成generator的方法,generator的特点,generator基础及高级应用场景,genera ...

  6. POJ1664(整数划分)

    放苹果 Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 30894   Accepted: 19504 Description ...

  7. js中的3种弹出式消息提醒(警告窗口,确认窗口,信息输入窗口)的命令式

    alert("A"); confirm("B");var name = confirm("B");if(name){ alert(" ...

  8. JAVA的SSH框架登录注册

    Struts 的MVC设计模式可以使我们的逻辑变得很清晰,主要负责表示层的显示. Spring 的IOC和AOP可以使我们的项目在最大限度上解藕. hibernate的就是实体对象的持久化了, 数据库 ...

  9. DLL 导出类

    MyMathFun.h #pragma once // #ifdef DLLCLASS_API // #define DLLCLASS_API _declspec(dllimport) // #els ...

  10. Asp.net mvc 知多少(八)

    本系列主要翻译自<ASP.NET MVC Interview Questions and Answers >- By Shailendra Chauhan,想看英文原版的可访问[http: ...