曲振飞的个人博客

专注于Web全栈开发、APP设计、网站建设

当前位置 : 主页 > 后端开发 > nodejs结合mongodb数据库制作增删改查实例

nodejs结合mongodb数据库制作增删改查实例

时间:2016-11-12 13:10:31 栏目:后端开发 作者:曲振飞 点击: 827

最近写了一个nodejs与mongodb数据库结合来实现一个简单的增删改查的Demo实例,在实现过程中遇到了很多问题,和大家一块分享下,其实在最开始本打算用express模块来搭建,这样会为我们省去很多时间和精力,但是在我们去学习一些模块之前,最好还是用一些原生的方法来实现,当理解一些底层的实现原理后,对于之后的模块或者一些框架的学习会更容易一些。

准备工作:

搭建nodejs环境
安装mongodb数据库,请查看mongoDB的安装与增删改查操作
安装mongoose 安装命令npm install mongoose

项目结构:

blob.png

项目预览:

blob.png

前端index.html页面

<DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>新闻发布系统</title>
    <style type="text/css">
            table{
                    width:800px;
                    border:1px solid #ddd;
                    margin:0 auto;
                    border-collapse:collapse;
                    font-size:14px;
            }
            th{
            	background:#eeeeee;
            }
            th,td{
                    border:1px solid #ddd;
                    padding:10px;
            }
            a{
            	margin-right: 10px;
            	text-decoration:none;
            }
    </style>
</head>
<body>
    <table>
        <caption><h1>新闻发布系统</h1></caption>
        <th>标题</th>
        <th>内容</th>
        <th>作者</th>
        <th>日期</th>
		<th>操作</th>
        <tbody id="tabBody">
        </tbody>
    </table>
<script type="text/javascript">
 	var tabBody = document.getElementById('tabBody');
    var xhr=new XMLHttpRequest();
    function getData(){
	    xhr.open("GET","http://192.168.1.4:3000/find",true);
	    xhr.onreadystatechange=function(){
	        if(xhr.readyState==4){
            	if(xhr.status==200){
                var str = JSON.parse(xhr.responseText);
                console.log(str);   
	                for(var i=0;i<str.length;i++){
				 		var tr = document.createElement("tr");
					 	var td1 = document.createElement("td");
					 	td1.innerHTML = str[i].title;
					 	var td2 = document.createElement("td");
					 	td2.innerHTML = str[i].content;
					 	var td3 = document.createElement("td");
					 	td3.innerHTML = str[i].author;
					 	var td4 = document.createElement("td");
					 	td4.innerHTML = str[i].date;
						var td5 = document.createElement("td");
					 	var insert_a = document.createElement("a");
					 	insert_a.setAttribute("id",str[i]._id);
					 	insert_a.setAttribute("href","insert.html");
					 	insert_a.innerHTML = "添加";
					 	var update_a = document.createElement("a");
					 	update_a.setAttribute("id",str[i]._id);
					 	update_a.setAttribute("href","update?"+str[i]._id);
					 	update_a.innerHTML = "更新";
					 	var delete_a = document.createElement("a");
					 	delete_a.setAttribute("id",str[i]._id);
					 	delete_a.setAttribute("onclick","del('"+str[i]._id+"')");
					 	delete_a.innerHTML = "删除";
						td5.appendChild(insert_a);
					 	td5.appendChild(update_a);
					 	td5.appendChild(delete_a);
					 	tr.appendChild(td1);
					 	tr.appendChild(td2);
					 	tr.appendChild(td3);
					 	tr.appendChild(td4);
						tr.appendChild(td5);
					 	tabBody.appendChild(tr);
				 	}
	            }
	        }
	    }
	    xhr.send(null);
	}
	getData();
	function del(obj){
		//alert(obj);
		xhr.open("post","http://192.168.1.4:3000/delete",true);
		xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		var str = "id="+obj;
		xhr.send(str);
		xhr.onreadystatechange=function(){
	        if(xhr.readyState==4){
            	if(xhr.status==200){
            		var data =xhr.responseText;
            		if(data == 1){
            			window.location.reload();
            		}
            	}
            }
        }
	}
</script>

后端页面app.js

var http = require("http");
var fs = require("fs");
var url = require("url");
var qs = require("querystring");
var ip = "192.168.1.4";
var port = 3000;
var mongos = require('./connection');
var server = new http.Server();
server.listen(port,ip);
server.on('request',(req,res) => {
    var pathname = url.parse(req.url).pathname;
    switch(pathname){
        case "" || "/":
            fs.readFile("./views/index.html",(err,content) => {
                if(err){
                    res.writeHead(404,{'Content-Type':'text/plain;charset=utf-8'});
                    res.write(err);
                    res.end();
                }else{
                    res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
                    res.write(content);
                    res.end();
                }
            });
            break;
        case "/find":
            selectData(mongos.news,function(result){
                    // 查询数据以JSON格式返回
                res.writeHead(200,{'Content-Type':'application/json;'});
                var str = JSON.stringify(result);
                res.write(str);
                res.end();
                mongos.dbClose();
            });
            break;
        case "/insert.html":		
            fs.readFile("./views/insert.html",(err,content) => {
                if(err){
                	res.writeHead(404,{"Content-Type":"text/plain;charset=utf-8"});
                	res.write(err);
                	res.end();
                }else{
                    res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});
                    res.write(content);
                    res.end();
                }
            });
            break;
		case "/doInsert":
			var datas = "";	
			req.addListener("data",function(postData){
				datas += postData;						
			});
			req.on("end",function(){
				var params = qs.parse(datas);
				var insertCont = {title:params['title'],content:params['content'],author:params['author'],date:params['date']};
                insertData(insertCont,function(result){
                    res.writeHead(302, {'Location':'http://192.168.1.4:3000/'})
                    res.end();
                });
			});
			break;
		case "/update":
			fs.readFile('./views/update.html',(err,content) => {
				if (err) {
					res.writeHead(404,{'Content-Type':'text/plain;charset=utf-8'});
					res.write(err);
					res.end();
				}else{
					res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
					res.write(content);
					res.end();
				}
			});
			break;
		case "/updateFind":
            var data = " ";
            req.on("data",function(postData){
            	data += postData;
            });
            req.on("end",function(){
            	var params = qs.parse(data);
            	var condition = params[' id'];
            	selectDataOne(condition,mongos.news,function(result){
	                res.writeHead(200,{'Content-Type':'application/json;'});
	                var str = JSON.stringify(result);
	                res.write(str);
	                res.end();
	                mongos.dbClose();
            	});
            });
			break;
		case "/doUpdate":
			var datas = "";	
			req.addListener("data",function(postData){
				datas += postData;						
			});
			req.on("end",function(){
				var params = qs.parse(datas);
                updateData(params,mongos.news,function(){
                    res.writeHead(302, {'Location':'http://192.168.1.4:3000/'})
                    res.end();
                    mongos.dbClose();
                });
			});
			break;
        case "/delete":
        	var data = "";
            req.addListener("data",function(postData){
				data += postData;				
			});
			req.on("end",function(){
				var params = qs.parse(data);
				deleteData(params['id'],mongos.news,function(str){
					console.log(str);
					res.writeHead(200,{'Content-Type':'application/json;'});
	                var strs = JSON.stringify(str);
	                res.write(strs);
	                res.end();
                    mongos.dbClose();
				});
			});
			break;
            default:
                var filename = pathname.substring(1);
                var type = getType(filename.substring(filename.lastIndexOf('.') + 1));
                console.log(filename + " *** " + type);
                fs.readFile(filename,(err,content) => {
                    if(err){
                            res.writeHead(404,{'Content-Type':'text/plain;charset=utf-8'});
                            res.write(err.message);
                            res.end();
                    }else{
                            res.writeHead(200,{'Content-Type':type});
                            res.write(content);
                            res.end();

                    }
                });
        }
});
function getType(endtag){ //用来加载css、js、图片等
    var type = null;
    switch(endtag){
        case "css":
                type = "text/css;charset=utf-8";
                break;
        case "js":
                type = "application/x-javascript;charset=utf-8";
                break;
        case "png":
                type = "image/png;charset=utf-8";
                break;
        case "htm":
                type = "text/html;charset=utf-8";
                break;
	case "html":
		type = "text/html;charset=utf-8";
		break;
            case "jpeg":
                    type = "image/jpeg";
                    break;
            case "jpg":
                    type = "image/jpeg";
                    break;
            default:
    }
    return type;
};
function selectData(myModel,callback){
    mongos.dbConnec();
    //var field = {name:1,age:1}; //待返回的字段
    myModel.find(function(error,result){
        if (error) {
                console.log(error);
        }else{
                callback(result);
        }
    });
}
function selectDataOne(condition,myModel,callback){
    var conditions = {_id:condition};
    // 6.查询条件
    var field = {name:1,age:1}; //待返回的字段
    myModel.findOne(conditions,function(error,result){
        if (error) {
                console.log(error);
        }else{
                callback(result);
        }
    });
}
// 插入操作
function insertData(insertCont,callback){
    var instance = new mongos.news(insertCont);
    instance.save(function(error,content){
        if (error) {
                console.log(error);
        }else{
            callback(content['_id']);
        }
        //关闭数据库链接
        //db.close();
    })  
}
function deleteData(id,myModel,callback){
    var condition = {_id:id};
    myModel.remove(condition,function(error){
        if (error) {
                console.log(error);
        }else{
                callback(1);
        }
        //关闭数据库链接
        //db.close();
    })
}
function updateData(params,myModel,callback){
    console.log(params);
    var condition = params['_id'];
    console.log(condition);
    var updateData = {title:params['title'],content:params['content'],author:params['author'],date:params['date']};
    console.log(updateData);
    myModel.update(condition,updateData,function(error,result){
            if (error) {
                    console.log(error);
            }else{
                    callback();
            }
    })
}

数据库链接页面connection.js

// 1.加载mongoose模块
var mongoose = require('mongoose');
// 2.链接mongoDB数据库
var db = mongoose.createConnection('mongodb://127.0.0.1:27017/qufei');
// 3.数据库链接错误信息
db.on("error",function(error){
        console.log(error);
});
// 4.定义模型
var Schema = mongoose.Schema;
var news = new Schema({
    title:{type: String},
    content:{type:String},
	author:{type:String,default:'qufei'},
    date:{type:Date,default:Date.now}
});
// 5.访问模型,第一个参数是集合(表名)。
var news  = db.model('news',news);
exports.news = news;
exports.dbConnec = function(){
	db = mongoose.createConnection('mongodb://127.0.0.1:27017/qufei');
}
exports.dbClose = function(){
	db.close();
}

前端更新页面update.html

<DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>更新信息 -- 新闻发布系统</title>
    <style type="text/css">
        table{
                width:800px;
                border:1px solid #ccc;
                margin:0 auto;
                border-collapse:collapse;
        }
        th,td{
                border:1px solid #ccc;
                padding:10px;
        }
    </style>
</head>
<body>
    <table>
        <caption><h1>新闻发布系统</h1></caption>
            <tbody id="tabBody">
            <form action="doUpdate" method="post">
            	<input type="text" id="_id" name="_id">
                <tr>
                    <td>标题</td>
                    <td><input type="text" id="title" name="title"></td>
                </tr>
                <tr>
                    <td>内容</td>
                    <td><input type="text" id="content" name="content"></td>
                </tr>
                <tr>
                    <td>作者</td>
                    <td><input type="text" id="author" name="author"></td>
                </tr>
                <tr>
                    <td>日期</td>
                    <td><input type="type" id="date" name="date"></td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="submit" name="dosubmit" value="更新">
                    </td>
                </tr>
                </form>
            </tbody>
    </table>
<script type="text/javascript">
	function urlPathname(){
		var url = window.location.href;
		var num = url.indexOf("?")+1;
		var urlpath = url.substring(num,url.length);
		return urlpath;
	}
	var url = urlPathname();
	var xhr=new XMLHttpRequest();
    xhr.open("post","http://192.168.1.4:3000/updateFind",true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	var str ="id="+url;
	xhr.send(str);
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
        	if(xhr.status==200){
	            var str = JSON.parse(xhr.responseText);
	            console.log(str);
	            document.getElementById('_id').value = str['_id'];
	            document.getElementById('title').value = str['title'];  
	            document.getElementById('content').value = str['content'];  
	            document.getElementById('author').value = str['author'];  
	            document.getElementById('date').value = str['date'];  
            }
        }
    }
</script>
</body>
</html>

前端插入页面insert.html

<DOCTYPE html>
<html>
<head>
        <meta charset="utf-8">
        <title>插入信息 -- 新闻发布系统</title>
        <style type="text/css">
                table{
                        width:800px;
                        border:1px solid #ccc;
                        margin:0 auto;
                        border-collapse:collapse;
                }
                th,td{
                        border:1px solid #ccc;
                        padding:10px;
                }
        </style>
</head>
<body>
    <table>
        <caption><h1>新闻发布系统</h1></caption>
	        <tbody id="tabBody">
	        <form action="doInsert" method="post">
	        	<tr>
	        		<td>标题</td>
	        		<td><input type="text" name="title"></td>
	        	</tr>
	        	<tr>
	        		<td>内容</td>
	        		<td><input type="text" name="content"></td>
	        	</tr>
	        	<tr>
	        		<td>作者</td>
	        		<td><input type="text" name="author"></td>
	        	</tr>
	        	<tr>
	        		<td>日期</td>
	        		<td><input type="date" name="date"></td>
	        	</tr>
	        	<tr>
	        		<td colspan="2">
	        			<input type="submit" name="dosubmit" value="提交">
	        		</td>
	        	</tr> 
	        	</form>
	        </tbody>
	   
    </table>
  </body>
</html>


关键字:

关于站长

曲振飞,一个热忠、从事于互联网的90后青年.专注于网站建站、网站设计及优化.以用户体验、WEB标准为主旨,将网站的整体设计与网页设计的相关原理紧密结合.