声明: 当查询到数据库数据后,对数据库数据进行遍历,可以采用toArray()函数,具体实现可以看第六点

1、本地安装mongodb

  安装包:https://www.mongodb.com/download-center/community

2、npm安装mongodb模块

  npm install mongodb --save-dev
  npm install ejs --save-dev

3、创建express-route路由模块文件 

var url=require('url');

    //封装方法改变res  绑定res.send()
function changeRes(res){
res.send=function(data){
res.writeHead(,{"Content-Type":"text/html;charset='utf-8'"});
res.end(data);
}
} //暴露的模块
var Server=function(){
var G=this; /*全局变量*/
//处理get和post请求
this._get={};
this._post={};
var app=function(req,res){
changeRes(res);
//获取路由
var pathname=url.parse(req.url).pathname;
if(!pathname.endsWith('/')){
pathname=pathname+'/';
}
//获取请求的方式 get post
var method=req.method.toLowerCase();
if(G['_'+method][pathname]){
if(method=='post'){ /*执行post请求*/
var postStr='';
req.on('data',function(chunk){
postStr+=chunk;
})
req.on('end',function(err,chunk) {
req.body=postStr; /*表示拿到post的值*/
G['_'+method][pathname](req,res); /*执行方法*/
})
}else{ /*执行get请求*/
G['_'+method][pathname](req,res); /*执行方法*/
}
}else{
res.end('no router');
}
} app.get=function(string,callback){
if(!string.endsWith('/')){
string=string+'/';
}
if(!string.startsWith('/')){
string='/'+string;
}
// /login/
G._get[string]=callback;
} app.post=function(string,callback){
if(!string.endsWith('/')){
string=string+'/';
}
if(!string.startsWith('/')){
string='/'+string;
}
G._post[string]=callback;
}
return app;
}
module.exports=Server();

4、连接并添加数据Demo

var http = require('http');
var app = require('./module/express-route');
var ejs = require('ejs'); /*mongodb连接设置*/
const MongoClient = require('mongodb').MongoClient;
const dburl = 'mongodb://localhost:27017';
const dbName = 'test';
const client = new MongoClient(dburl);
/**/
http.createServer(app).listen(''); /**
* 添加数据
*/
app.get('/add',function (req,res) {
client.connect(function(err) {
if(err){//连接失败
console.log("Connected fail to server");
}
//连接成功
console.log("Connected successfully to server");
const db = client.db(dbName);
db.collection('shop').insertOne({'name':"name-yangwenjie","age":},function (error,result) {
if(error){
console.log("insert database faile");
}
console.log("insert database successfully");
client.close();
})
});
})

5、nodejs操作mongdb增删改查操作并联合ejs联合使用

/**
* 添加数据
*/
app.get('/add',function (req,res) {
client.connect(function(err) {
if(err){//连接失败
console.log("Connected fail to server");
}
//连接成功
console.log("Connected successfully to server");
const db = client.db(dbName);
db.collection('shop').insertOne({'name':"name-yangwenjie","age":},function (error,result) {
if(error){
console.log("insert database faile");
}
console.log("insert database successfully");
client.close();
})
});
}); /**
* 查找数据和EJS一起使用
*/
app.get('/find',function (req,res) {
var list = [];
client.connect(function (err) {
if (err) {//连接失败
console.log("Connected fail to server");
}
//连接成功
console.log("Connected successfully to server");
const db = client.db(dbName);
var result = db.collection('shop').find({ "age" : });
result.each(function (err,data) {
if(err){
console.log(err);
} else {
if(data!=null){
list.push(data);
console.log("你好:"+list[].name);
ejs.renderFile('练习/views/index.ejs',{list:list},function (err,data) {
if(err){
console.log(err);
return false;
}
console.log(data);
res.send(data);
});
}else {//循环完成
console.log("循环完成"+list);
}
}
})
});
}); /**
* 删除文档
*/
app.get('delete',function (req,res) {
client.connect(function (err) {
if(err){
console.log("Connected fail to server");
}
console.log("Connected successfully to server");
const db = client.db(dbName);
//文档和过滤条件
db.collection('shop').deleteOne({"name":"name-yangwenjie"},function (err,result) {
if(err){
console.log("delete fail to server");
}
console.log("delete successfully to server");
console.log(result);
})
})
}) /**
* 更新文档数据
*/
app.get('/update',function (req,res) {
client.connect(function (err) {
if(err){
console.log("连接数据库失败!");
}
console.log("连接数据库成功!");
var db = client.db(dbName);
db.collection('shop').updateOne({"name":"yangwenjie"},{$set:{"age":}},function (err,result) {
if(err){
console.log("更新数据失败");
}
console.log("更新数据成功!");
console.log(result);
}) })
})

6、遍历查找的数据建议采用toArray()进行遍历

 var result = db.collection('user').find(req.body);
result.toArray(function (err,data) {
//console.log(data.username);
//console.log(data.length);
if(data.length>){
//登陆成功
req.session.userinfo=data[];
//res.render('product');
res.redirect('/product');
}else {
//登陆失败
res.send("<script>alert('登陆失败');location.href='/login'</script>")
}
})

注意:mongodb配置代码

const  MongoClient = require('mongodb').MongoClient; //引用mongodb
const dburl = 'mongodb://localhost:27017'; //数据库url
const dbName = 'test'; //数据库名
const client = new MongoClient(dburl); //创建一个客户端
client.connect(function(err) {
if(err){
console.log("Connected fail to server");
}
console.log("Connected successfully to server");
const db = client.db(dbName);
//添加数据库操作代码
client.close();
});

具体可以参考mongodb关于nodejs的官方文档:http://mongodb.github.io/node-mongodb-native/3.1/quick-start/quick-start/

nodejs之mongodb操作的更多相关文章

  1. nodejs对mongodb数据库的增删改查操作(转载)

    首先要确保mongodb的正确安装,安装参照:http://docs.mongodb.org/manual/tutorial/install-mongodb-on-debian-or-ubuntu-l ...

  2. 69.nodejs对mongodb数据库的增删改查操作

    转自:https://www.cnblogs.com/sexintercourse/p/6485381.html 首先要确保mongodb的正确安装,安装参照:http://docs.mongodb. ...

  3. nodejs实践-MongoDB

    nodejs实践-MongoDB laiqun@msn.cn Contents 1. 特点: 2. 开始使用 3. 使用Mongoose操作MongoDB 4. 在express中使用,组织数据库相关 ...

  4. Nodejs中Mongodb使用

    Mongodb使用 打开解压后的Mongodb文件夹,新建data.logs文件夹,并在logs文件夹中新建mongodb.log文档. 添加后Mongod文件夹示意图: 用cmd命令行启动Mongo ...

  5. NodeJS+Express+MongoDB

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

  6. Linux环境下安装NodeJS和mongoDB

    前面的话 本文将详细介绍如何下Linux环境下安装NodeJS和mongoDB NodeJS [1]使用二进制包安装 1.在官网下载Linux环境下的NodeJS安装包 2.通过xftp软件将安装包上 ...

  7. nodejs+express+mongodb简单的例子

    简单的介绍下node+express+mongodb这三个东西.node:是运行在服务器端的程序语言,表面上看过去就是javascript一样的东西,但是呢,确实就是服务器语言,个人觉得在一定层次上比 ...

  8. Mongoose使用——nodejs结合mongodb

    0. 前言: Mongoose是NodeJS的驱动,不能作为其他语言的驱动.Mongoose有两个特点: 通过关系型数据库的思想来设计非关系型数据库 基于mongodb驱动,简化操作 Mongooos ...

  9. 【重点突破】—— Nodejs+Express+MongoDB的使用基础

    前言:最近学习vue和react的高阶项目,都需要和Nodejs+Express+MongoDB结合实现全栈开发.这里结合实例Demo和所学项目集中总结一下这部分服务端的基础知识. 一.Express ...

随机推荐

  1. Shell脚本之sed详解

    在编写shell脚本的过程中,我们经常需要使用sed流编辑器和awk对文本文件进行处理. 一.什么是sed? sed 是一种在线编辑器,它一次处理一行内容.sed是非交互式的编辑器.它不会修改文件,除 ...

  2. Delphi Timer组件

  3. 个人总结的J2EE目前知道的涵盖面,从大方向入手,多写单元测试,加强基础

    JEE Development process: java SE 普通语法,,异常处理,数据结构,循环,面向对象,泛型, 属性,反射,多线程,线程池,锁, lambada,异步编程,并发 框架spri ...

  4. CMMI分为哪几个等级?

    一共分为五个等级. 1.CMMI一级,完成级.在完成级水平上,企业对项目的目标与要做的努力很清晰.项目的目标得以实现. 2.CMMI二级,管理级.在管理级水平上,企业在项目实施上能够遵守既定的计划与流 ...

  5. Aspect表达式

    任意公共方法的执行:execution(public * *(..))任何一个以“set”开始的方法的执行:execution(* set*(..))AccountService 接口的任意方法的执行 ...

  6. c#图像处理的简单算法

    原文链接:https://blog.csdn.net/wchstrife/article/details/78984735 使用C#进行图像处理前言之前一直认为图像处理是一件很高大上的事情,在一门选修 ...

  7. zabbix监控Nginx模板

    前提条件: nginx模块安装了http_stub_status_module和nginx_upstream_check_module: 在nginx的配置文件中配置上: location /stat ...

  8. Redis常用数据类型底层数据结构分析

    Redis是一种键值(key-Value)数据库,相对于关系型数据库,它也被叫作非关系型数据库 Redis中,键的数据类型是字符串,但是为了非富数据存储方式,方便开发者使用,值的数据类型有很多 字符串 ...

  9. 字典树Trie--实现敏感词过滤

    序言 Trie树 资料 https://blog.csdn.net/m0_37907797/article/details/103272967?utm_source=apphttps://blog.c ...

  10. Flash大文件断点续传功能

    一.概述 所谓断点续传,其实只是指下载,也就是要从文件已经下载的地方开始继续下载.在以前版本的HTTP协议是不支持断点的,HTTP/1.1开始就支持了.一般断点下载时才用到Range和Content- ...