mongoDB & Nodejs 访问mongoDB (二)
非常详细的文档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 (二)的更多相关文章
- mongoDB & Nodejs 访问mongoDB (一)
最近的毕设需要用到mongoDB数据库,又把它拿出来再学一学,下盘并不是很稳,所以做一些笔记,不然又忘啦. 安装 mongoDB & mongoVUE mongoDB: https://www ...
- MongoDB最简单的入门教程之二 使用nodejs访问MongoDB
在前一篇教程 MongoDB最简单的入门教程之一 环境搭建 里,我们已经完成了MongoDB的环境搭建. 在localhost:27017的服务器上,在数据库admin下面创建了一个名为person的 ...
- 使用nodejs 访问mongodb
我使用了 express 框架 目录结构 db.js 文件 function connectionDB(hostname, port) { //注释地方暂时没有使用.是把官方代码照抄下来 // var ...
- 使用 MongoDB shell访问MongoDB
- NodeJS+Express+MongoDB
一.MongoDB MongoDB是开源,高性能的NoSQL数据库:支持索引.集群.复制和故障转移.各种语言的驱动程序丰富:高伸缩性:MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言 ...
- MongoDB最简单的入门教程之五-通过Restful API访问MongoDB
通过前面四篇的学习,我们已经在本地安装了一个MongoDB数据库,并且通过一个简单的Spring boot应用的单元测试,插入了几条记录到MongoDB中,并通过MongoDB Compass查看到了 ...
- 使用Spring访问Mongodb的方法大全——Spring Data MongoDB查询指南
1.概述 Spring Data MongoDB 是Spring框架访问mongodb的神器,借助它可以非常方便的读写mongo库.本文介绍使用Spring Data MongoDB来访问mongod ...
- 使用Spring访问Mongodb的方法大全——Spring Data MongoDB
1.概述 Spring Data MongoDB 是Spring框架访问mongodb的神器,借助它可以非常方便的读写mongo库.本文介绍使用Spring Data MongoDB来访问mongod ...
- nodejs学习笔记二——链接mongodb
a.安装mongoose库用来链接mongodb数据库 安装mongodb数据库参考mongodb安装 前言(怨言) 本来是想安装mongodb库来链接mongodb的,命令行到nodejs工程目录: ...
随机推荐
- RAC执行root.sh报libcap.so.1: cannot open shared object file
Failed to create keys in the OLR, rc = 127, Message: /opt/app/11.2.0/grid/bin/clscfg.bin: error whil ...
- mysql 使用sqldump来进行数据库还原
MYSQLdump参数详解 mysqldump备份: 复制代码代码如下: mysqldump -u用户名 -p密码 -h主机 数据库 a -w “sql条件” –lock-all-tables > ...
- cgLib生成动态代理
package com.stono.cglib; import java.lang.reflect.Method; import net.sf.cglib.proxy.Enhancer; import ...
- javascript实现页面滚屏效果
当我们浏览网页的时候,时常会碰到可以滚动屏幕的炫酷网页,今天笔者对这一技术进行简单实现,效果不及读者理想中那般炫酷,主要针对滚屏的技术原理和思想进行分享和分析.本示例在页面右侧有五个数字标签,代表五个 ...
- OpenCV教程二 - Mat对象与它各种用法
学习OpenCV大家都会遇到一个对象叫做Mat,此对象非常神奇,支持各种操作.很多初学者因此被搞得头晕脑胀,它各种用法太多太杂,搞得初学者应接不暇,感觉有心无力.无处下手之感.这里我们首先要正本清源, ...
- There is no getter for property named 'userId' in 'class java.lang.String'
[ERROR] 2017-01-18 04:37:06:231 cn.dataenergy.common.CenterHandlerExceptionResolver (CenterHandlerEx ...
- Bootstrap入门(十九)组件13:页头与缩略图
Bootstrap入门(十九)组件13:页头与缩略 1.页头 2.默认的缩略图 3.自定义缩略图 页头组件能够为 h1 标签增加适当的空间,并且与页面的其他部分形成一定的分隔.它支持 h1 标签内内嵌 ...
- Spark:一个独立应用
[TOC] Spark:一个独立应用 关于构建 Java和Scala 在Java和Scala中,只需要给你的应用添加一个对于spark-core的Maven依赖. Python 在Python中,可以 ...
- Professional C# 6 and .NET Core 1.0 - What’s New in C# 6
本文为转载,学习研究 What's New in C# 6 With C# 6 a new C# compiler is available. It's not only that a source ...
- [CSS3] 学习笔记-CSS3常用操作
1.对齐操作 使用margin属性进行水平对齐:使用position进行左右对齐:使用float属性进行左右对齐. <!doctype html> <html> <hea ...