node.js与mongoDB实现数据的增删改查(并用拼接字符串的方式响应给客户端)
前言:写的不足之处还望大佬们指出,当然也希望自己能给初学者一点点帮助。----一只好学的程序猿
ps:非小白直接从2.2开始
1:准备工作(捋一捋思路)
- 搭建网站服务器,实现客户端与服务器端的通讯
- 连接数据库,创建用户集合,向集合中插入文档
- 当用户访问/list时,将所有用户信息查询出来
- 将用户信息和表格HTML进行拼接并将拼接结果返回至客户端
- 当用户访问/add时,呈现表单页面,并实现添加用户功能
- 访问/modify时,呈现修改页面,并实现修改信息功能
- 访问/delete时,实现用户删除功能
//注释后边字母(cwen,tido,!,import)为自定义注释高亮(无用)
//cwen搭建网站服务器,实现客户端与服务器端的通讯
//todo连接数据库,创建用户集合,向集合中插入文档
//cwen当用户访问/list时,将所有用户信息查询出来 1)实现路由功能,2)实现用户列表页面 3)从数据库中查询用户信息,将用户信息展示在列表中
//!将用户信息和表格HTML进行拼接并将拼接结果返回至客户端
//cwen当用户访问/add时,呈现表单页面,并实现添加用户功能
//import访问/modify时,呈现修改页面,并实现修改信息功能 1)增加页面路由,呈现页面 1.点击修改按钮时,将用户id传递至当前页面 2.从数据库查询当前信息并展示。 2)实现用户修改功能 1)指定表单请求地址以及请求方式 2)接受客户端传递过来的修改信息 找到用户 接用户信息更改为最新
//cwen访问/delete时,实现用户删除功能
2:开始干活(完成上述功能)
- 搭建网站服务器qie连接数据库:
const http = require('http');
const mongoose = require('mongoose');
//playground本地数据库名字
mongoose.connect('mongodb://localhost/playground', { useUnifiedTopology: true, useNewUrlParser: true })
.then(() => console.log('数据库连接成功'))
.catch(err => console.log(err, '数据库连接失败'))
//!建立服务器start
const app = http.createServer();
app.on('request', (req, res) => {
res.end('OK');
});
app.listen(3000);
console.log('服务器搭建完成,端口3000');
- 创建用户集合,向集合中插入文档:
1)创建集合:
const userSchema = new mongoose.Schema({
name: {
type: String,
require: true,
minlength: 2,
maxlength: 5
},
age: {
type: Number,
min: 18,
max: 80
},
hobbies: [String],
email: String,
password: String
});
//创建集合返回集合构造函数
const User = mongoose.model('User', userSchema);
//将User开放出去,方便其他模块调用
module.exports = User;
以上操作均为铺垫(熟悉node.js客户端与服务器端的交互及mongodb的简单数据集合创建),以下部分与其代码方面无关联(希望不会干扰到思路)。
2)插入文档(在powerShell中通过命令插入):
3)文档源码:
{ "_id": { "$oid": "5c09f1e5aeb04b22f8460965" }, "name": "张三", "age": 20, "hobbies": ["足球", "篮球", "橄榄球"], "email": "[email protected]", "password": "123456" } { "_id": { "$oid": "5c09f236aeb04b22f8460967" }, "name": "李四", "age": 10, "hobbies": ["足球", "篮球"], "email": "[email protected]", "password": "654321" } { "_id": { "$oid": "5c09f267aeb04b22f8460968" }, "name": "王五", "age": 25, "hobbies": ["敲代码"], "email": "[email protected]", "password": "123456" } { "_id": { "$oid": "5c09f294aeb04b22f8460969" }, "name": "赵六", "age": 50, "hobbies": ["吃饭", "睡觉", "打豆豆"], "email": "[email protected]", "password": "123456" } { "_id": { "$oid": "5c09f2b6aeb04b22f846096a" }, "name": "王二麻子", "age": 32, "hobbies": ["吃饭"], "email": "[email protected]", "password": "123456" } { "_id": { "$oid": "5c09f2d9aeb04b22f846096b" }, "name": "狗蛋", "age": 14, "hobbies": ["打豆豆"], "email": "[email protected]", "password": "123456" }
3:创建路由分辨请求方式并完成需求:
1)删,改,查 (均为GET请求方式)
ps:此处GET,POST均为大写,小写无效(可通过 const method = req.method.toLowerCase(),转换为小写)
(1)建立model文件夹,并建立文件index.js(用于数据库连接)
const mongoose = require('mongoose');
//!连接数据库start
//!数据库连接 27017是mongodb数据库的默认端口
mongoose.connect('mongodb://localhost/playground', { useUnifiedTopology: true, useNewUrlParser: true })
.then(() => console.log('数据库连接成功'))
.catch(err => console.log(err, '数据库连接失败'))
(2)在model下建立user.js(用于创建用户集合)
//index.js也引入了mongoose 不会发生性能上的浪费 在node.js内部有缓存机制,只要第一次引入了第三方模块,下一次直接从缓存中拿。
const mongoose = require('mongoose');
//创建用户集合
const userSchema = new mongoose.Schema({
name: {
type: String,
require: true,
minlength: 2,
maxlength: 5
},
age: {
type: Number,
min: 18,
max: 80
},
hobbies: [String],
email: String,
password: String
});
//创建集合返回集合构造函数
const User = mongoose.model('User', userSchema);
//将User开放出去,方便其他模块调用
module.exports = User;
(3)捋一捋:访问位于路径栏中,故提交方式为GET。model文件夹同级下创建app.js并写入如下(细节处含注释):
const http = require('http');
const url = require('url');
const querystring = require('querystring');
//引入连接数据库文件
require('./model/index.js');
//也可直接在此处写出
// const mongoose = require('mongoose');
// mongoose.connect('mongodb://localhost/playground', { useUnifiedTopology: true, useNewUrlParser: true })
// .then(() => console.log('数据库连接成功'))
// .catch(err => console.log(err, '数据库连接失败'))
//引入创建集合文件
const User = require('./model/user.js');
//也可直接在此处写出
//const userSchema = new mongoose.Schema({
// name: {
// type: String,
// require: true,
// minlength: 2,
// maxlength: 5
// },
// age: {
// type: Number,
// min: 18,
// max: 80
// },
// hobbies: [String],
// email: String,
// password: String
// });
// //创建集合返回集合构造函数
// const User = mongoose.model('User', userSchema);
//!建立服务器start
const app = http.createServer();
app.on('request', async(req, res) => {
//请求方式
const method = req.method;
//请求地址(pathnam获取pathname,query获取id)
const { pathname, query } = url.parse(req.url, true);
if (method == 'GET') {
//呈现列表页面
if (pathname == '/list') {
//查询用户信息
let users = await User.find();
// console.log(users);
//cwen字符串拼接完成动态表格
let list = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/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 list = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/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(list);
} else if (pathname == '/modify') {
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/[email protected]/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3>修改用户</h3>
// 表单通过post方式提交参数 id通过地址栏get方式传递
<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') {
//拿到传入的id并进行删除数据
// res.end(query.id);
await User.findOneAndDelete({ _id: query.id }).then(doc => console.log(doc)).catch(err => (err, 'not can delete'));
res.writeHead(301, {
location: '/list'
});
res.end();
}
}
*此处用拼接字符串(非引号,为tab键上面键)
2)增(为POST提交方式)
(1)捋一捋:其中包括增加和修改(修改页面跳转为GET,修改后提交方式为POST),接上app.js(细节处含注释)
else if (method == 'POST') {
if (pathname == '/add') {
//接受用户提交信息
let formData = '';
//接收post参数
req.on('data', param => {
formData += param;
})
//post参数接收完毕
req.on('end', async() => {
//querystring中parse方法获取user对象
let user = querystring.parse(formData);
// console.log(querystring.parse(formData));
//将用户提交信息添加到数据库
await User.create(user);
//301代表重定向
//location 跳转地址
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);
// console.log(querystring.parse(formData));
//将用户提交信息添加到数据库(实现更新)
await User.updateOne({ _id: query.id }, user);
//301代表重定向
//location 跳转地址
res.writeHead(301, {
location: '/list'
});
res.end();
})
}
}
// res.end('ok')
});
app.listen(3000);
console.log('服务器搭建完成,端口3000');
3)PowerShell使用命令执行app.js(node .\app.js )并请求本地服务器文件(localhost:3000/list)即可。
OVER