nodejs之mongodb操作
声明: 当查询到数据库数据后,对数据库数据进行遍历,可以采用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(200,{"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('8001'); /** * 添加数据 */ 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":28},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":28},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" : 38}); result.each(function (err,data) { if(err){ console.log(err); } else { if(data!=null){ list.push(data); console.log("你好:"+list[0].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":38}},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>0){ //登陆成功 req.session.userinfo=data[0]; //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/
本文来自博客园,作者:小白啊小白,Fighting,转载请注明原文链接:https://www.cnblogs.com/ywjfx/p/10400832.html