node.js连接mongodb实现增删改查

使用node.js平台连接mongodb数据库;

实现效果

mongodb是一个非关系型数据库,数据结构类似与json,在实现连接之前,需要安装好node.js平台和mongodb数据库。为了显示效果,写了一个页面方便观察。一开始数据库里是没有数据的。
在这里插入图片描述
页面最终效果。
功能介绍
写入
我们使用添加功能。在输入框中输入信息,点击写入按钮,数据就会保存到数据库中,并显示在页面上,
在这里插入图片描述
在这里插入图片描述
提示
在这里插入图片描述

查询
数据,就要查找的数据输入到输入框中,点击查询项目。
在这里插入图片描述
如果找到了提示找到了。没找到提示没找到。
在这里插入图片描述
修改数据
在输入框中输入旧数据和新数据,点击改变按钮。
比如进张三改成李四

在这里插入图片描述
改变之后
在这里插入图片描述
我们可以看到页面张三被改成了李四;
查看数据库

在这里插入图片描述
删除
将要删除的数据填写好,点击删除;
点击前
在这里插入图片描述
点前后
在这里插入图片描述
全部删除
全部删除,可以删除所有数据
在这里插入图片描述
一点都没了
在这里插入图片描述
在这里插入图片描述

以上就是实现的功能

实现步骤

第一步

打开命令行,运行mongodb数据库 。运行好了之后,在最下方会显示数据库端口号
在这里插入图片描述
其中27017就是数据库地址

第二步

创建项目,把需要的模块都下好,这里用了 express框架,mongodb数据库模块,将需要用的函数封装一下,方便使用;
需要使用的函数

//第一步引入数据库,和数据库地址】
//引入数据库模块
const mongodb=require('mongodb').MongoClient
//引入数据库地址
const url='mongodb://localhost:27017';
//把连接数据库的操作封装为一个函数,不同的操作在写不同的函数;
function _connect(callback){
	//连接数据库两参数,数据库地址和回调函数
	mongodb.connect(url,function(err,db){
		if(err) throw err;
		//db连接以后的数据
		callback(db);
	})
}
//添加数据 dbname 数据库名  colname 集合名  obj数据 callback 回调
module.exports.insert=function(dbname,colname,obj,callback){
	
      _connect(function(db){
		  //检测保存的数据是不是一个数组,不是数组就变成数组
		  if(!(obj instanceof Array)){
			  obj=[obj];
		  }
		  // 插入数据
		  db.db(dbname).collection(colname).insertMany(obj,(err,data)=>{
			     if(err) throw err;
				  //关闭数据库文件。
				  db.close();
				  callback(data);
		   })
		  
	  });
};
//添加查询数据
//dbname要插查询的数据   colname  集合名   obj要查询的数据   callback回调函数
module.exports.find=function(dbname,colname,obj,callback){
	    _connect(function(db){
			db.db(dbname).collection(colname).find(obj).toArray((err,data)=>{
				if(err) throw err;
				db.close();
				callback(data);
			})
		})
}
//修改数据
module.exports.updata=function(dbname,colname,obj,obj2,callback){
	_connect(function(db){
		db.db(dbname).collection(colname).updateMany(obj,{$set:obj2},(err,data)=>{
			if(err) throw err;
			db.close();
			callback(data);
		})
	})
}
//删除数据
module.exports.del=function(dbname,colname,obj,callback){
	_connect(function(db){
		db.db(dbname).collection(colname).deleteMany(obj,(err,obj)=>{
			if(err) throw err;
			db.close();
			callback(obj);
		})
	})
}
//删除全部数据
module.exports.remove=function(dbname,colname,obj,callback){
	_connect(function(db){
		db.db(dbname).collection(colname).deleteMany(obj,(err)=>{
			if(err) throw err;
			db.close();
			callback;
		})
	})
}

到这里,数据库就连接完毕了,只需要导包使用就可以了。

第三步

服务器代码
引入上面写的数据库代码

const express=require('express');
const querystring=require('querystring');
const url=require('url');
const mongodb=require('./www/js/mongodbFunction.js');
const app=express();
app.use('/www',express.static('./www'));

//插入数据
app.get('/insert',(req,res)=>{
	let data={'data':req.query.data};
    mongodb.insert('example','data',data,(a)=>{
		 res.send(a);
	});
});
//查找数据
app.get('/find',(req,res)=>{
	let data={'data':req.query.data};
	mongodb.find('example','data',data,(a)=>{
		res.send(a);
	})
	
});
//改变数据
app.get('/updata',(req,res)=>{
	let old={'data':req.query.old};
	let news={'data':req.query.news};
	mongodb.updata('example','data',old,news,(a)=>{
		res.send(a);
	})
})
//删除数据
app.get('/del',(req,res)=>{
	let data={'data':req.query.data};
	mongodb.del('example','data',data,(a)=>{
        res.send(a);
	})
});
//删除全部数据
app.get('/remove',(req,res)=>{
        mongodb.remove('example','data',{},()=>{
		     // res.send('true'); 		 
    	});
});
//用来每次显示数据
app.get('/show',(req,res)=>{
	mongodb.find('example','data',{},(c)=>{
		res.send(c);
	 });
});

app.listen('9999');

html文件

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>增删改查</title>
		<script src='./js/vue.js'></script>
		<script src='./js/axios.js'></script>
		<script src='js/jquery.js'></script>
        <style>
			*{
				margin:0;
				padding:0;
			}
			.app{
				margin:0 auto;
				width:1000px;
				height: 400px;
				border:2px solid grey;
			}
			.app .long{
				height:50px;
				text-align: center;
				line-height:50px;
				background-color:#B2DBA1
			}
			.app .left{
				width:300px;
				height:350px;
				float:left;
			}
			.app .right{
				width:700px;
				height:350px;
				float:left;
			}
			.app .right .top{
				width:700px;
				height:280px;
				overflow-y:scroll;
			}
			.app .right .bottm{
				border-top:1px solid black;
				overflow:hidden;
				height:69px;
				text-align:center;
			}
			.app li{
				list-style-type:none;
				cursor:pointer;
			}
			.app li:hover{
				color:blueviolet;
			}
			.app button:hover{
				background-color: red;
				color:white;
			}
			.app .left>ul>li{
				margin-top:2rem;
				margin-left:2rem;
			}
			.blue{
				color:blue;
			}
		</style>
	</head>
	<body>
		<div id='app' class='app'>
			<div class='long'><h1>增删改查</h1></div>
			<div class='left'>
				<ul>
					<li><b>增加数据</b><br><input placeholder='数据' v-model='insert'><button v-on:click='insert_f()'>写入</button></li>
					<li><b>查询数据</b><br><input placeholder='数据' v-model='find'><button v-on:click='find_f()'>查询</button></li>
					<li><b>改变数据</b>
					    <ul>
					         <li><input placeholder='原数据' v-model='updata'></li>
							 <li><input placeholder='修改后的数据' v-model='updatas'></li>
				     	</ul><button v-on:click='updata_f()'>改变</button></li>
					<li><b>删除数据</b><br><input placeholder='数据' v-model='del'><button v-on:click='del_f()'>删除</button></li>
					<li v-on:click='removeAll()'>删除全部数据</li>
				</ul>
			</div>
			<div class='right'>
				<b><b class='blue'>{{listLength}}</b>条数据</b>
				<div class=top>
					<ol>
						<li v-for='(item,index) in list'>{{index}}.{{item.data}}</li>
					</ol>
				</div>
				<div class='bottm'>
					{{inform}}
				</div>
			</div>
		</div>
	</body>
	<script>
	
		const vue=new Vue({
			el:'#app',
			data:{
				list:[],
				listLength:0,
				insert:'',
				find:'',
				updata:"",
				updatas:"",
				del:'',
				inform:'没有操作',
			},
			methods:{
				insert_f:function(){
					axios.get('http://localhost:9999/insert',{params:{"data":this.insert}}).then((a)=>{
						let temp=a.data.ops[0].data;
						this.inform=`添加了:${temp}`;
					}).catch((s)=>{
						this.insform='添加失败';
					});
					this.show();
				},
				find_f:function(){
					axios.get('http://localhost:9999/find',{params:{"data":this.find}}).then((a)=>{
						let temp=a.data[0].data;
						this.inform='找到了'+temp+'';
					}).catch((s)=>{
						this.inform='查询的数据不存在';
					})
					this.show();
				},
				updata_f:function(){
					axios.get('http://localhost:9999/updata',{params:{'old':this.updata,'news':this.updatas}}).then((a)=>{
			           let news=a.config.params.news;
					   let old=a.config.old.params.old;
					   this.inform='<b>'+old+'</b>替换成了<b>'+news+'</b>';
					}).catch((s)=>{
						this.infrom='替换失败';
					})
					this.show();
				},
				del_f:function(){
					axios.get('http://localhost:9999/del',{params:{"data":this.del}}).then((a)=>{
						let temp=a.config.params.data;
						this.inform=`删除了${temp}`;
					}).catch((s)=>{
						this.inform='数据不存在';
					})
					this.show();
				},
				removeAll:function(){
					axios.get('http://localhost:9999/remove').then((a)=>{
						console.log(a);
						console.log('删除成功了');
					}).catch((s)=>{
						console.log('删除失败');
					});
					this.show();
				},
				show:function(){
					axios.get('http://localhost:9999/show').then((a)=>{
						this.list=a.data;
						this.listLength=this.list.length;
						console.log('显示成功');
					}).catch((s)=>{
						console.log('显示失败');
					})
				},
			}
		})
		vue.show();
	</script>
</html>

以上就是全部代码

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值