node.js 增删改查(原始)

index.js 连接数据库
const mongoose = require('mongoose')
//数据库连接27017是mongodb数据库的默认端口
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true })
.then(() => console.log('数据库连接成功'))
.catch(() => console.log('数据库连接失败'))
user.js 创建用户集合规则
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)
module.exports = User;
app.js 请求处理
const http = require('http');
const url = require('url')
const querystring = require('querystring')
// 连接数据库
require('./model/index.js')
const User = require('./model/user.js')
// 创建服务器
const app = http.createServer();
// 为服务器对象添加请求事件
app.on('request', async(req, res) => {
// 请求方式
const method = req.method;
// 请求地址
const { pathname, query } = url.parse(req.url, true)
console.log(query, '123')
console.log(pathname)
if (method == "GET") {
listtt = ''
if (pathname == '/list') {
let data = await User.find()
listtt += `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="title col-md-10 col-md-offset-1">
<div class="head">
<a href="/add" class="btn btn-success">添加用户</a>
</div>
<div class="content">
<table class="table table-striped">
<thead>
<tr>
<th>用户名</th>
<th>年龄</th>
<th>爱好</th>
<th>邮箱</th>
<th$>操作</th>
</tr>
</thead>
<tbody>
`
data.forEach(item => {
listtt +=
`
<tr>
<td>${item.name}</td>
<td>${item.age}</td>
<td>
`
item.hobbies.forEach(item => {
listtt += `
<span>${item}</span>
`
})
listtt += `
</td>
<td>${item.email}</td>
<td>
<a href="/edit?id=${ item._id }" class="btn btn-default">修改</a>
<a href="/delete?id=${item._id}" class="btn btn-danger">删除</a>
</td>
</tr>
`
});
listtt += `
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
</html> `
res.end(listtt)
} else if (pathname == '/add') {
add = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="title col-md-10 col-md-offset-1">
<h1>添加用户</h1>
<form method="post">
<div class="form-group">
<label for="exampleInputEmail1">姓名</label>
<input name="name" type="text" class="form-control" id="exampleInputEmail1" placeholder="请输入姓名">
</div>
<div class="form-group">
<label for="exampleInputPassword1">年龄</label>
<input name="age" type="text" class="form-control" id="exampleInputPassword1" placeholder="请输入年龄">
</div>
<div class="form-group">
<label for="exampleInputEmail1">密码</label>
<input name="password" type="password" class="form-control" id="exampleInputEmail1" placeholder="请输入密码">
</div>
<div class="form-group">
<label for="exampleInputPassword1">邮箱</label>
<input name="email" type="email" class="form-control" id="exampleInputPassword1" placeholder="请输入邮箱">
</div>
<div class="checkbox">
<label>
<input type="checkbox" value="篮球" name=" hobbies" > 篮球
</label>
<label>
<input type="checkbox" value="足球" name=" hobbies" > 足球
</label>
<label>
<input type="checkbox"value="橄榄球" name=" hobbies" > 橄榄球
</label>
<label>
<input type="checkbox" value="敲代码" name=" hobbies" > 敲代码
</label>
<label>
<input type="checkbox" value="抽烟" name=" hobbies" > 抽烟
</label>
<label>
<input type="checkbox" value="喝酒" name=" hobbies"> 喝酒
</label>
<label>
<input type="checkbox" value="烫头" name=" hobbies" > 烫头
</label>
</div>
<button type="submit" class="btn btn-success">提交</button>
</form>
</div>
</div>
</div>
</body>
</html>
`
res.end(add)
} else if (pathname == '/edit') {
let user = await User.findOne({ _id: query.id });
let hobbies = ['足球', '篮球', '橄榄球', '敲代码', '抽烟', '喝酒', '烫头']
let edit = ``
var editid = user._id
edit += `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="title col-md-10 col-md-offset-1">
<h1>编辑用户</h1>
<form method="post" action="/edit?id="${user._id}">
<div class="form-group">
<label for="exampleInputEmail1">姓名</label>
<input name="name" type="text" class="form-control" id="exampleInputEmail1" placeholder="请输入姓名" value="${user.name}">
<input name="useid" type="hidden" class="form-control" value="${user._id}">
</div>
<div class="form-group">
<label for="exampleInputPassword1">年龄</label>
<input name="age" type="text" class="form-control" id="exampleInputPassword1" placeholder="请输入年龄" value="${user.age}">
</div>
<div class="form-group">
<label for="exampleInputEmail1">密码</label>
<input name="password" type="password" class="form-control" id="exampleInputEmail1" placeholder="请输入密码" value="${user.password}">
</div>
<div class="form-group">
<label for="exampleInputPassword1">邮箱</label>
<input name="email" type="email" class="form-control" id="exampleInputPassword1" placeholder="请输入邮箱" value="${user.email}">
</div>
<div class="checkbox">
`
hobbies.forEach(item => {
console.log(item)
//判断当前循环项在不在用户的爱好数组里
let isHobby = user.hobbies.includes(item);
if (isHobby) {
edit += `
<label>
<input type="checkbox" checked name=" hobbies" value="${item}"> ${item}
</label>
`
} else {
edit += `
<label>
<input type="checkbox" name=" hobbies" value="${item}">${item}
</label>
`
}
})
edit += `
</div>
<button type="submit" class="btn btn-success">提交修改</button>
</form>
</div>
</div>
</div>
</body>
</html>`
res.end(edit)
} else if (pathname == '/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 = '';
//接受post参数
req.on('data', param => {
formData += param;
})
//post 参数接受完毕
req.on('end', async() => {
let user = querystring.parse(formData.replace(/\+/g, ""))
console.log(user['hobbies'])
//将提交的数据提交到数据库中
await User.create(user);
// 301 代表重定向
// location 跳转地址
res.writeHead(301, {
Location: '/list'
});
res.end();
})
} else if (pathname == '/edit') {
//接受用户提交的信息
let formData = '';
//接受post参数
req.on('data', param => {
formData += param;
})
//post 参数接受完毕
req.on('end', async() => {
let user = querystring.parse(formData.replace(/\+/g, ""))
//将提交的数据提交到数据库中
await User.updateOne({ _id: user.useid }, { name: user.name, age: user.age, password: user.password, email: user.email, hobbies: user.hobbies });
// 301 代表重定向
// location 跳转地址
res.writeHead(301, {
Location: '/list'
});
res.end();
})
}
}
})
console.log('连接服务器成功')
app.listen(3000)
node.js 增删改查(原始)的更多相关文章
- MybatisMapper 映射框架(增删改查 原始模式)
//增删改查 package TestDemo; import java.io.IOException; import java.io.InputStream; import java.util.Da ...
- js 增删改查
<html><head lang="en"> <meta charset="UTF-8"> <title>< ...
- JS 增删改查操作XML
效果图: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <titl ...
- js 增删改查方法
push() 向数组的末尾添加一个或多个元素 pop() 删除数组内部并返回数组的最后一个元素 shift() 把数组内部的第一个元素从其中删除,并返回第一个元素的值 unshift() 向数组外部的 ...
- JS增删改查localStorage实现搜索历史功能
<script type="text/javascript"> var referrerPath = "@ViewBag.ReferrerPath" ...
- webpack4+express+mongodb+vue 实现增删改查
在讲解之前,我们先来看看效果如下所示: 1)整个页面的效果如下: 2) 新增数据效果如下: 3) 新增成功如下: 4) 编辑数据效果如下: 5) 编辑成功效果如下: 6) 删除数据效果如下: 7) 删 ...
- Node.js、express、mongodb 入门(基于easyui datagrid增删改查)
前言 从在本机(win8.1)环境安装相关环境到做完这个demo大概不到两周时间,刚开始只是在本机安装环境并没有敲个Demo,从周末开始断断续续的想写一个,按照惯性思维就写一个增删改查吧,一方面是体验 ...
- Node.js + MySQL 实现数据的增删改查
通过完成一个 todo 应用展示 Node.js + MySQL 增删改查的功能.这里后台使用 Koa 及其相应的一些中间件作为 server 提供服务. 初始化项目 $ mkdir node-cru ...
- Node.js之mysql增删改查
1.安装库 npm install mysql 2.编写db.js(用作公共模块) //连接MySQL数据库 var mysql = require("mysql"); var p ...
- node.js入门学习(四)--Demo图书的增删改查
需求:图书的增删改查,图书数据保存在data.json文件中. 1.Demo结构: 2.首先下载安装node.js,配置环境变量:参考博客 3.项目初始化 1)创建项目根目录node-hello,进入 ...
随机推荐
- PHP实现没有数据库提交form表单到后台并且显示出数据列表(Vuejs和Element-UI前端设计表单)
1.情境:如果你新建了个网站,却没有数据库服务器,如何把你的表单信息,提交到服务端后台,收集数据. 2.思路:如果用传统的form action 提交到一个form.php页面,此时只能存储一次数据, ...
- 远程协助软件哪个好,IT远程支持用什么软件
软件行业做售后支持,有时候需要远程控制客户电脑以实现远程协助,远程解决客户问题. IT远程支持用什么软件比较好?这个我们可以逐个分析下. 一.QQ远程 一看就不专业,的确也不专业.QQ远程协助可以实现 ...
- pageoffice6实现Word在线套打
使用Word可以套打,其实套打一般就是将要打印的内容分毫不差的打印到已有的模板中去,比如奖状.证书.票据.报表等都可以使用套打完成. 方法一: 将Word页面排版的和打印纸中的页面完全相同,然后将打印 ...
- Axure和墨刀——两款原型设计工具介绍
Axure与墨刀是两款在原型设计领域广受欢迎的工具,各具特点和优势: Axure: Axure RP是一款功能强大的原型设计工具,广泛应用于交互设计和用户体验设计领域.它提供了丰富的交互元素库.高保真 ...
- 免费考AI OCP认证,附通关秘籍!
这是一个能让你快速熟悉AI相关技能的考试,由Oracle官方提供,而且限时免费. 它就是OCI Generative AI Professional. 可以看到,目前免费政策正在执行,到今年的7月31 ...
- Redis CPU过高排查
Redis CPU过高 测试环境经常卡住,经过排查是鉴权的不稳定,鉴权又经过redis查询.来到redis机器,发现cpu100%.redis的锅 top redis竟然cpu使用率达到100% 保存 ...
- Linux中根据关键字获取某一行的行号
[root@localhost ~]# cat test.txt 123213 ehualu.server ehualu.docker 10.0.0.10 ehualu.server ehualu.d ...
- Android OpenMAX(一)漫谈
在开始正式的学习前,我们先来聊一聊Android音视频开发中的一些问题.感受与想法.(有一点要事先说明,我的问题与答案.想法并不一定正确,请读者带着审慎的思考来阅读,后续的文章也是一样,希望读者边阅读 ...
- shell脚本入门学习
1 参考 [尚硅谷]Shell脚本从入门到实战_哔哩哔哩_bilibili 本文为上面链接的课程学习记录. 2 基础 shell脚本需要shell解释器进行执行,shell解释器就是一个应用程序,有多 ...
- pands基础--数据结构:Series
从本文开始介绍pandas的相关知识. pandas含有是数据分析工作变得更快更简单的高级数据结构和操作工具,是基于numpy构建的. 本章节的代码引入pandas约定为:import pandas ...