案例:用户信息增删改查

18 篇文章 1 订阅
10 篇文章 0 订阅

在这里插入图片描述
案例截图,代码在资源里
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
向数据库中导入数据
在这里插入图片描述

//搭建网站服务器,实现客户端与服务器端的通信
const http = require('http');
//连接数据库,创建用户集合,向集合中插入文档

const mongoose = require('mongoose');
const url = require('url');
//对参数的格式进行转换
const querystring = require('querystring');

数据库链接 27017是mongodb数据库的默认端口
mongoose.connect('mongodb://localhost/playground', {useNewUrlParser: true, useUnifiedTopology: true})
	.then(() => console.log('数据库连接成功'))
	.catch(() => console.log('数据库连接失败'))

创建用户集合规则
const UserSchema = new mongoose.Schema({
	name: {
		type: String,
		required: true,
		minlength: 2,
		maxlength: 20
	},
	age: {
		type: Number,
		min: 18, 
		max: 80
	},
	password: String,
	email: String,
	hobbies: [String]
})

//创建集合 返回集合构造函数
const User = mongoose.model('User', UserSchema);


使用集合规则创建集合

创建服务器
const app = http.createServer();

为服务器对象添加请求事件
///
//当用户访问/list时,将所有用户信息查询出来
//(实现路由功能,呈现用户列表页面,从数据库中查询用户信息并将用户信息展示在列表中)
//路由功能:先获取用户的请求方式和请求地址,并对其进行判断。


//将用户信息和表格HTML进行拼接并将拼接结果相应回客户端
app.on('request', async (req, res) => {
	//请求方式
	const method = req.method;
	//对象解构,将parse获得对象下面的pathname属性获取出来
	//query保存了get请求参数,但是默认是字符窜类型,但是将parse的第二个变量改为true就会变为对象类型
	//这个对象里面保存了id属性
	const {pathname, query} = url.parse(req.url, true);

	if (method == 'GET') {
		// GET数据的请求或者页面的呈递
		// 呈现用户列表页面
		if (pathname == '/list') {
			//查询用户信息
			let users = await User.find();
			// console.log(users);
			// html字符串
			let list = `<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>用户列表</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>
<body>
	<div class="container">
		<h6>
			<a href="/add" class="btn btn-primary">添加用户</a>
		</h6>
		<table class="table table-striped table-bordered">
			<tr>
				<td>用户名</td>
				<td>年龄</td>
				<td>爱好</td>
				<td>邮箱</td>
				<td>操作</td>
			</tr>
		`;
		//对数组进行循环,用forEach
		users.forEach(item => {
			list +=`
<tr>
				<td>${item.name}</td>
				<td>${item.age}</td>
				<td>
				
			`;
			item.hobbies.forEach(item => {
				list += `<span>${item}</span>`
			})

			list += `
</td>
				<td>${item.email}</td>
				<td>
					<a href="/remove?id=${item._id}" class="btn btn-danger btn-xs">删除</a>
					<a href="/modify?id=${item._id}" class="btn btn-success btn-xs">修改</a>
				</td>
			</tr>
			`;
		})

		list += `
	</table>
	</div>
</body>
</html>
		`;
			res.end(list);
		} else if (pathname == '/add') {
			//将用户访问/add时,呈现表单页面,并实现添加用户信息功能
			let add = `
			<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>用户列表</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>
<body>
	<div class="container">
		<h3>添加用户</h3>
		<form method="post" action="/add">
		  <div class="form-group">
		    <label>用户名</label>
		    <input name="name" type="text" class="form-control" placeholder="请填写用户名">
		  </div>
		  <div class="form-group">
		    <label>密码</label>
		    <input name="password" type="password" class="form-control" placeholder="请输入密码">
		  </div>
		  <div class="form-group">
		    <label>年龄</label>
		    <input name="age" type="text" class="form-control" placeholder="请填写邮箱">
		  </div>
		  <div class="form-group">
		    <label>邮箱</label>
		    <input name="email" type="email" class="form-control" placeholder="请填写邮箱">
		  </div>
		  <div class="form-group">
		    <label>请选择爱好</label>
		    <div>
		    	<label class="checkbox-inline">
		    	  <input type="checkbox" value="足球" name="hobbies"> 足球
		    	</label>
		    	<label class="checkbox-inline">
		    	  <input type="checkbox" value="篮球" name="hobbies"> 篮球
		    	</label>
		    	<label class="checkbox-inline">
		    	  <input type="checkbox" value="橄榄球" name="hobbies"> 橄榄球
		    	</label>
		    	<label class="checkbox-inline">
		    	  <input type="checkbox" value="敲代码" name="hobbies"> 敲代码
		    	</label>
		    	<label class="checkbox-inline">
		    	  <input type="checkbox" value="抽烟" name="hobbies"> 抽烟
		    	</label>
		    	<label class="checkbox-inline">
		    	  <input type="checkbox" value="喝酒" name="hobbies"> 喝酒
		    	</label>
		    	<label class="checkbox-inline">
		    	  <input type="checkbox" value="烫头" name="hobbies"> 烫头
		    	</label>
		    </div>
		  </div>
		  <button type="submit" class="btn btn-primary">添加用户</button>
		</form>
	</div>
</body>
</html>`;
res.end(add)
		} else if (pathname == '/modify') {
			//当用户访问/modify时,呈现修改页面,并实现修改用户信息功能
增加页面路由 呈现页面
///     1.在点击修改按钮的时候,将用户ID传递到当前页面
///     2.从数据库中查询当前用户信息 将用户信息展示到页面中
///实现用户修改功能
///		1.指定表单的提交地址以及提交方式
///		2.接收客户端传递过来的修改信息 找到用户 将用户信息更改为最新的
			let user = await User.findOne({_id: query.id});
			let hobbies = ['足球','篮球','橄榄球','敲代码','抽烟','喝酒','烫头'];
			// console.log(user)
			//将用户访问/add时,呈现修改用户表单页面,并实现添加用户信息功能
			let modify = `
			<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>用户列表</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head> 
<body>
	<div class="container">
		<h3>修改用户</h3>
		<form method="post" action="/modify?id=${user._id}">
		  <div class="form-group">
		    <label>用户名</label>
		    <input value="${user.name}" name="name" type="text" class="form-control" placeholder="请填写用户名">
		  </div>
		  <div class="form-group">
		    <label>密码</label>
		    <input value="${user.password}" name="password" type="password" class="form-control" placeholder="请输入密码">
		  </div>
		  <div class="form-group">
		    <label>年龄</label>
		    <input value="${user.age}" name="age" type="text" class="form-control" placeholder="请填写邮箱">
		  </div>
		  <div class="form-group">
		    <label>邮箱</label>
		    <input value="${user.email}" name="email" type="email" class="form-control" placeholder="请填写邮箱">
		  </div>
		  <div class="form-group">
		    <label>请选择爱好</label>
		    <div>
		    	
		    `;

		    hobbies.forEach(item => {
		    	//判断当前循环项是否在用户的爱好数据组里。
		    	let isHobby = user.hobbies.includes(item);
		    	if (isHobby) {
		    		modify += `<label class="checkbox-inline">
		    	  <input type="checkbox" value="${item}" name="hobbies" checked> ${item}
		    	</label>`;
		    	} else {
		    		modify += `<label class="checkbox-inline">
		    	  <input type="checkbox" value="${item}" name="hobbies"> ${item}
		    	</label>`;
		    	}
		    })

		modify += `</div>
		  </div>
		  <button type="submit" class="btn btn-primary">修改用户</button>
			</form>
			</div>
		</body>
		</html>`;
//把modify这个变量响应给客户端
res.end(modify)
		} else if (pathname == '/remove') {
			//当用户访问/delete时,实现用户删除功能
			// res.end(query.id)
			await User.findOneAndDelete({_id: query.id});
			res.writeHead(301, {
				Location: '/list'
			});
			res.end();
		}
	} else if (method == 'POST') {
		// 有一些功能
		if (pathname == '/add') {
			//接收用户提交的信息
			let formData = '';
			//接受form参数
			req.on('data', param => {
				formData += param;
			})
			//post参数接收完毕
			req.on('end', async () => {
				let user = querystring.parse(formData);
				//将信息返回到数据库中
				//create方法中的第一个变量是对象类型
				await User.create(user);
				//writeHead 通过响应头的方式跳转到其他页面
				//301代表重定向,实际上就是跳转到其他页面的意思
				//location 跳转地址
				res.writeHead(301, {
					Location: '/list'
				});
				res.end();
			})
			
		} else if (pathname == '/modify') {
			//接收用户提交的信息
			let formData = '';
			//接受form参数
			req.on('data', param => {
				formData += param;
			})
			//post参数接收完毕
			req.on('end', async () => {
				let user = querystring.parse(formData);
				//将信息返回到数据库中
				//create方法中的第一个变量是对象类型
				await User.updateOne({_id: query.id},user);
				//writeHead 通过响应头的方式跳转到其他页面
				//301代表重定向,实际上就是跳转到其他页面的意思
				//location 跳转地址
				res.writeHead(301, {
					Location: '/list'
				});
				res.end();
			})
		}
	}
});
监听端口
app.listen(3000);

以上为完整的js代码

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值