1、数据库相关概念
database
collection:一组数据的集合,js中的数组
document:文档,一条具体的数据,js中的对象
field:字段,文档中属性名字,js中对象的属性
2、Monggoose第三方包
使用node.js操作MongoDB需要依赖node.js第三方包mongoose
安装monggoose:
npm install mongoose
3、启动MongoDB
命令行工具中运行:
net start mongoDB即可启动MongoDB,否则MongoDB无法连接
net stop mongodv
net start mongodb
4、数据库连接
使用MongoDB提供的connect方法即可以连接数据库
const mongoose=require('mongoose')
mongoose.connect('mongodb://localhost/testdb',{useNewUrlParser:true})
.then(()=>console.log('数据库连接成功'))
.catch(err=>console.log('数据库连接失败',err))
5、创建数据库
MongoDB不需要显示创建数据库,如果正在使用的数据库不存在,mongodb会自动创建
6、创建集合
创建集合分两步:
1、对集合设定规则
2、创建集合,创建monogoose.Schema构造函数的实例即可创建集合
//创建集合规则
const courseSchema=new monogoose.Schema({
name:String,
author:String,
isPublished:Boolean
})
//创建集合并应用规则
const Course=mongoose.model('Course',courseSchema);//集合名称需大写,但是在MongoDB里面是courses
7、创建文档(集合实例)
实际上就是用构造函数创建Course集合的实例
const course=new Course({
name:'node.js course',
author:'heima teacher',
tags:['node','backend'],
isPublished:true
})
//将数据保存在数据库中
course.save()
完整代码应该是:
const mongoose=require('mongoose')
mongoose.connect('mongodb://127.0.0.1/testdb',{useNewUrlParser:true})
.then(()=>console.log('数据库连接成功'))
.catch(err=>console.log('数据库连接失败',err))
const courseSchema=new mongoose.Schema({
name:String,
author:String,
isPublished:Boolean
})
const Course=mongoose.model('Course',courseSchema);
const course=new Course({
name:'node.js course',
author:'heima teacher',
tags:['node','backend'],
isPublished:true
})
//将数据保存在数据库中
course.save()
8、创建文档的另外一种方式create
使用create方法创建文档
Course.create({
name:'javascript基础',
author:'黑马讲师',
isPublished:true,
},(err,doc)=>{
//错误对象
console.log(err)
//正确对象
console.log(doc)
})
10、MongoDB数据库导入数据
- mongoImport要去下载,并且拷贝到安装目录的bin目录下
- 要将bin目录添加到环境变量的系统变量的path路径中
文件下载及用法参考
https://blog.csdn.net/weixin_45147894/article/details/115511146
mongoimport -d testdb -c users --file ./user.json
本笔记示例数据为:
{"_id":{"$oid":"5c09f1e5aeb04b22f8460965"},"name":"张三","age":20,"hobbies":["足球","篮球","橄榄球"],"email":"zhangsan@itcast.cn","password":"123456"}
{"_id":{"$oid":"5c09f236aeb04b22f8460967"},"name":"李四","age":10,"hobbies":["足球","篮球"],"email":"lisi@itcast.cn","password":"654321"}
{"_id":{"$oid":"5c09f267aeb04b22f8460968"},"name":"王五","age":25,"hobbies":["敲代码"],"email":"wangwu@itcast.cn","password":"123456"}
{"_id":{"$oid":"5c09f294aeb04b22f8460969"},"name":"赵六","age":50,"hobbies":["吃饭","睡觉","打豆豆"],"email":"zhaoliu@itcast.cn","password":"123456"}
{"_id":{"$oid":"5c09f2b6aeb04b22f846096a"},"name":"王二麻子","age":32,"hobbies":["吃饭"],"email":"wangermazi@itcast.cn","password":"123456"}
{"_id":{"$oid":"5c09f2d9aeb04b22f846096b"},"name":"狗蛋","age":14,"hobbies":["打豆豆"],"email":"goudan@163.com","password":"123456"}
11、MongoDB的增删改查–查询文档(记录)
默认查找全部文档,查询的结果为数组
const mongoose=require('mongoose')
mongoose.connect('mongodb://127.0.0.1/testdb',{useNewUrlParser:true})
.then(()=>console.log('数据库连接成功'))
.catch(err=>console.log('数据库连接失败',err))
const courseSchema=new mongoose.Schema({
name:String,
author:String,
isPublished:Boolean
})
//使用规则创建集合
const Course=mongoose.model('Course',courseSchema);
//在集合中查询文档
Course.find()
.then(result=>console.log(result))
12、find的条件查找
以对象的形式呈现查找条件
返回结果是一个数组,
const mongoose=require('mongoose')
mongoose.connect('mongodb://127.0.0.1/testdb',{useNewUrlParser:true})
.then(()=>console.log('数据库连接成功'))
.catch(err=>console.log('数据库连接失败',err))
//1.创建集合的规则
const userSchema=new mongoose.Schema({
name:String,
age:Number,
hobbies:Array,
email:String,
password:String
})
//2.使用规则创建集合
const User=mongoose.model('users',userSchema);
//在集合中查询文档
User.find({
_id:'5c09f2d9aeb04b22f846096b'
})
.then(result=>console.log(result))
13、findOne的条件查找一条文档(记录)
返回当前结果的第一条数据
也可以传入一个对象作为查找条件
//2.使用规则创建集合
const User=mongoose.model('users',userSchema);
//在集合中查询文档
User.findOne()
.then(result=>console.log(result))
14、find的查询大于小于
//匹配大于、小于
$gt:大于
$lt:小于
//匹配包含
$in:数组
//选择要查询的字段
select(‘字段1 字段2’)
//将数组按照某个字段排序
sort(‘age’)
//skip跳过多少条数据,limit限制查询数量
skip(2).limit(2)
//1.创建集合的规则
const userSchema=new mongoose.Schema({
name:String,
age:Number,
hobbies:Array,
email:String,
password:String
})
//2.使用规则创建集合
const User=mongoose.model('users',userSchema);
//在集合中查询文档,匹配大于小于
User.find({age:{$gt:20,$lt:50}})
.then(result=>console.log(result))
console.log('-----------')
//匹配包含
User.find({hobbies:{$in:['敲代码']}})
.then(result=>console.log(result))
console.log('-----------')
//包含字段
User.find().select('name age')
.then(result=>console.log(result))
console.log('-----------')
//排序负号是降序
User.find({age:{$gt:30,$lt:50}}).sort('age')
.then(result=>console.log(result))
console.log('-----------')
//略过数量
User.find().skip(2).limit(3)
.then(result=>console.log(result))
console.log('-----------')
15、findeOneAndDelete删除文档(记录)
查找并删除第一条文档,返回被删除的文档
//2.使用规则创建集合
const User=mongoose.model('users',userSchema);
//在集合中查询文档,匹配大于小于
User.findOneAndDelete({name:'王五'})
.then(result=>{
console.log(result)
})
16、deleteMany删除多条文档(记录)
删除多个文档,返回的是删除的文档数量
//2.使用规则创建集合
const User=mongoose.model('users',userSchema);
//在集合中查询文档,匹配大于小于
User.deleteMany()
.then(result=>{
console.log(result)
})
17、updateOne更新单个文档
返回 一个对象,对象是修改信息但不是修改后的对象,此外,如果update的信息多余查找的信息,这个updataOne不会删除原有的记录,而是添加了一条新的记录
//2.使用规则创建集合
const User=mongoose.model('users',userSchema);
//更新
User.updateOne({查询条件},{要修改的值})
.then(result=>console.log(result))
案例1,
//2.使用规则创建集合
const User=mongoose.model('users',userSchema);
//在集合中查询文档,匹配大于小于
User.updateOne({name:'狗蛋'},{name:'张三丰',age:100})
.then(result=>console.log(r
案例2,
//2.使用规则创建集合
const User=mongoose.model('users',userSchema);
//在集合中查询文档,匹配大于小于
User.updateOne({name:'狗蛋'},{name:'张三丰'})
.then(result=>console.log(r
以上两个案例产生的修改结果是不一样的
18、updateMany更新多个文档
//2.使用规则创建集合
const User=mongoose.model('users',userSchema);
//更新
User.updateMany({查询条件},{要修改的值})
.then(result=>console.log(result))
案例
//2.使用规则创建集合
const User=mongoose.model('users',userSchema);
//在集合中查询文档,匹配大于小于
User.updateMany({},{age:56})
.then(result=>console.log(result))
19、mongoose验证
再创建集合规则时,可以设置当前字段的验证规则,验证失败就是显示插入失败
- required:true 必传字段
- minlength:20 最小长度
- maxlength:最大长度
- trim:true 去除两边的空格
- min:xx 最小值
- max:xx 最大值
- type:类型值
- default:xx 默认值
- enum:【枚举值1,枚举值2,枚举值3,…】
//1.创建集合的规则
const postSchema=new mongoose.Schema({
title:{
type:String,
// required:true
required:[true,'请传入文章标题保存'],
minlength:[2,'最小长度不能小于2'],
maxlength:[5,'最大长度不能大于5'],
trim:true
}
},
age:{
type:Number,
min:18,
max:100
},
publishDate:{
type:Date,
default:Date.now
},
category:{
type:String,
enum:{
values:['html','css','javascript'],
message:'分类名称要子啊一定的范围内才可以'
}
},
author:{
type:String,
Validate:{
validator:v=>{
//返回布尔值,true成功,false失败,v是用来检验的值
return v && v.length>4
}
//自定义错误信息
message:'传入的值不符合验证规则'
}
}
)
//2.使用规则创建集合
const Post=mongoose.model('Post',postSchema)
Post.create({}).then(result=>console.log(result))
.catch(error=>{
//获取错误信息对象
const err=error.errors//errors是内置错误对象
//循环遍历错误信息对象
for(let attr in err){
//将错误信息打印到控制台中
console.log(err[attr]['message'])
}
})
20、集合关联
通常不同集合的数据之间是有关系的,如文章集合里面的字段(属性)也对应另外一个用户集合的字段(属性),如文章集合有id,用户集合有name,这两个集合就是有关联的。
步骤:
- 使用id对集合进行关联
- 使用populate方法进行关联集合查询
const mongoose=require('mongoose')
mongoose.connect('mongodb://127.0.0.1/testdb',{useNewUrlParser:true})
.then(()=>console.log('数据库连接成功'))
.catch(err=>console.log('数据库连接失败',err))
//1.创建用户集合,这里规则和集合写在了一起
const User=mongoose.model('User',new mongoose.Schema({
name: {
type:String,
required:true
}
}) )
//2.创建用户集合
const Post=mongoose.model('Post',new mongoose.Schema({
title:{type:String},
//使用id将文章集合和作者集合记性关联
author:{
type:mongoose.Schema.Types.ObjectId,
ref:'User'//关联到用户集合
},
})
)
/*
//3、创建用户文档(记录)
User.create({name:'ithejima'}).then(result=>console.log(result))
//4、创建文章文档(记录)
Post.create({title:'heimatitle',author:'60a9c8ff60a9727198b5850f'}).then(result=>console.log(result))
*/
//联合查询
Post.find()
.populate('author')
.then(result=>console.log(result))
20.5、node连接mysql数据库
1、安装mysql模块
npm install mysql --save
2、配置数据库连接对象等
//导入模块
const mysql=require('mysql')
//连接数据库,创建连接对象,设置连接参数
let connection=mysql.createConnection({
host:'localhost',//mysql的默认端口3306不用再这里写出来,因为这是在mysql中设置的,不在node里写
user:'root',
password:'******',
database:'myemployees'
});
//创建连接
connection.connect()
//执行查询语句,表名需要加反引号
//使用别名是为了方便调用具体的字段
//insert into等语句可以直接使用模板字符串
let querystr='select employee_id as id,first_name as first,last_name as last from `employees` '
connection.query(querystr,function(err,results,field){
if (err){
// throw err
console.log('查询错误')
}
console.log('the solution is:'+results[0].id+' '+results[0].first+'·'+results[0].last)
})
connection.end()
21、用户信息增删改查案例
未分离版本
/*
1.搭建网站服务器,实现客户端与服务器端的通信
2.连接数据库,创建用户集合,向集合中插入文档
3.当用户访问/list时,将所有用户信息查询出来
3.1实现路由功能
3.2呈现用户列表页面
3.3从数据库中查询用户信息 将用户信息展示在列表中
4.将用户信息和表格HTML进行拼接并将拼接结果响应回客户端
5.当用户访问/add时,呈现表单页面,并实现添加用户信息功能
6.当用户访问/modify时,呈现修改页面,并实现修改用户信息功能
修改用户信息分为两大步骤
6.1.增加页面路由 呈现页面
6.1.1.在点击修改按钮的时候 将用户ID传递到当前页面
6.1.2.从数据库中查询当前用户信息 将用户信息展示到页面中
6.2.实现用户修改功能
6.2.1.指定表单的提交地址以及请求方式
6.2.2.接受客户端传递过来的修改信息 找到用户 将用户信息更改为最新的
7.当用户访问/delete时,实现用户删除功能
*/
//搭建服务器的必须模块
const http=require('http')
//导入mongoose第三方模块
const mongoose=require('mongoose')
//导入url模块
const url=require('url');
//导入queryString模块
const querystring=require('querystring')
//连接数据库,27017是数据库的默认端口
mongoose.connect('mongodb://localhost/playground', {useNewUrlParser: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)
//使用mongoimport -d playground将数据user.json的数据导入到playground数据库中
// mongoimport -d playground -c users --file ./user.json
//***********************************************
//创建服务器
const app=http.createServer();
//为服务器对象添加请求事件
app.on('request',async (req,res)=>{//这里有异步请求
//请求方式
const method=req.method;
const {pathname,query}=url.parse(req.url,true)//第三方模块url对请求地址进行解析,返回的是一个对象,使用对象解析方式对这个对象进行解析
// console.log(pathname)
//请求方式为get时
if(method=='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>`;
//对数据进行循环操作
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'){
//显现添加用户表单页面
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'){
//申明user用来接受从修改用户连接传递来的用户对象
let user=await User.findOne({_id:query.id})
//创建一个数组来接受爱好
let hobbies=['足球','篮球','橄榄球','敲代码','抽烟','喝酒'];
console.log(user)
//显现修改用户表单页面
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>`;
res.end(modify)
}
//删除用户路由
else if(pathname=='/remove'){
// res.end(query.id)
await User.findOneAndDelete({_id:query.id})
res.writeHead(301,{
Location:'/list'
})
res.end()
}
}else if (method=='POST'){
//用户添加功能
if (pathname=='/add'){//添加信息直接在add路由中处理
//接收用户提交的信息
let formData='';//页面提交参数的拼接字符串
//接收post参数
req.on('data',(param)=>{//正在接收参数时
formData+=param;
})
//接收post参数完毕
req.on('end',async ()=>{
let user=querystring.parse(formData)//使用querstring将拼接好的参数字符串转换为对象,使用了第三方模块
//将用户提交的信息添加到数据库中
await User.create(user);
res.writeHead(301,{
Location:'/list'
})
res.end()
})
}else if (pathname=='/modify'){
//接收用户提交的信息
let formData='';//页面提交参数的拼接字符串
//接收post参数
req.on('data',(param)=>{//正在接收参数时
formData+=param;
})
//接收post参数完毕
req.on('end',async ()=>{
let user=querystring.parse(formData)//使用querstring将拼接好的参数字符串转换为对象,使用了第三方模块
//将用户提交的信息添加到数据库中
await User.updateOne({_id:query.id},user);
res.writeHead(301,{
Location:'/list'
})
res.end()
})
}
}
})
//监听端口
app.listen(3000)```
#### <font color=green>22、用户信息增删改查案例分离版
分离出两个模块1:数据库连接模块
**/user/model/index.js**
```php
//导入mongoose第三方模块
const mongoose=require('mongoose')
//连接数据库,27017是数据库的默认端口
mongoose.connect('mongodb://localhost/playground', {useNewUrlParser:true})
.then(()=>{console.log('数据库连接成功')})
.catch(()=>{console.log('数据库连接失败')})
分离出两个模块2:用户模块
/user/user/user.js
//导入mongoose第三方模块
const mongoose=require('mongoose')
//创建集合规则
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)
//开放User集合
module.exports = User;
字符串拼接见模板引擎
在页面再将这俩模块引进使用
/*
1.搭建网站服务器,实现客户端与服务器端的通信
2.连接数据库,创建用户集合,向集合中插入文档
3.当用户访问/list时,将所有用户信息查询出来
3.1实现路由功能
3.2呈现用户列表页面
3.3从数据库中查询用户信息 将用户信息展示在列表中
4.将用户信息和表格HTML进行拼接并将拼接结果响应回客户端
5.当用户访问/add时,呈现表单页面,并实现添加用户信息功能
6.当用户访问/modify时,呈现修改页面,并实现修改用户信息功能
修改用户信息分为两大步骤
6.1.增加页面路由 呈现页面
6.1.1.在点击修改按钮的时候 将用户ID传递到当前页面
6.1.2.从数据库中查询当前用户信息 将用户信息展示到页面中
6.2.实现用户修改功能
6.2.1.指定表单的提交地址以及请求方式
6.2.2.接受客户端传递过来的修改信息 找到用户 将用户信息更改为最新的
7.当用户访问/delete时,实现用户删除功能
*/
//搭建服务器的必须模块
const http=require('http')
//导入url模块
const url=require('url');
//导入queryString模块
const querystring=require('querystring')
//引入连接数据库模块
require('./model/index')
//引入用户模块
const User=require('./user/user')
//使用mongoimport -d playground将数据user.json的数据导入到playground数据库中
// mongoimport -d playground -c users --file ./user.json
//***********************************************
//创建服务器
const app=http.createServer();
//为服务器对象添加请求事件
app.on('request',async (req,res)=>{//这里有异步请求
//请求方式
const method=req.method;
const {pathname,query}=url.parse(req.url,true)//第三方模块url对请求地址进行解析,返回的是一个对象,使用对象解析方式对这个对象进行解析
// console.log(pathname)
//请求方式为get时
if(method=='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>`;
//对数据进行循环操作
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'){
//显现添加用户表单页面
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'){
//申明user用来接受从修改用户连接传递来的用户对象
let user=await User.findOne({_id:query.id})
//创建一个数组来接受爱好
let hobbies=['足球','篮球','橄榄球','敲代码','抽烟','喝酒'];
console.log(user)
//显现修改用户表单页面
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>`;
res.end(modify)
}
//删除用户路由
else if(pathname=='/remove'){
// res.end(query.id)
await User.findOneAndDelete({_id:query.id})
res.writeHead(301,{
Location:'/list'
})
res.end()
}
}else if (method=='POST'){
//用户添加功能
if (pathname=='/add'){//添加信息直接在add路由中处理
//接收用户提交的信息
let formData='';//页面提交参数的拼接字符串
//接收post参数
req.on('data',(param)=>{//正在接收参数时
formData+=param;
})
//接收post参数完毕
req.on('end',async ()=>{
let user=querystring.parse(formData)//使用querstring将拼接好的参数字符串转换为对象,使用了第三方模块
//将用户提交的信息添加到数据库中
await User.create(user);
res.writeHead(301,{
Location:'/list'
})
res.end()
})
}else if (pathname=='/modify'){
//接收用户提交的信息
let formData='';//页面提交参数的拼接字符串
//接收post参数
req.on('data',(param)=>{//正在接收参数时
formData+=param;
})
//接收post参数完毕
req.on('end',async ()=>{
let user=querystring.parse(formData)//使用querstring将拼接好的参数字符串转换为对象,使用了第三方模块
//将用户提交的信息添加到数据库中
await User.updateOne({_id:query.id},user);
res.writeHead(301,{
Location:'/list'
})
res.end()
})
}
}
})
//监听端口
app.listen(3000)