node.js 增删改查(原始)
2021-06-05 13:01
阅读:310
YPE html>
标签:nod upd number ima cti pre app 对象 div
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 += `Document ` res.end(listtt) } else if (pathname == ‘/add‘) { add = `添加用户
` data.forEach(item => { listtt += ` 用户名 年龄 爱好 邮箱 操作 ` }); listtt += ` ${item.name} ${item.age} ` item.hobbies.forEach(item => { listtt += ` ${item} ` }) listtt += ` ${item.email} 修改 删除 Document ` res.end(add) } else if (pathname == ‘/edit‘) { let user = await User.findOne({ _id: query.id }); let hobbies = [‘足球‘, ‘篮球‘, ‘橄榄球‘, ‘敲代码‘, ‘抽烟‘, ‘喝酒‘, ‘烫头‘] let edit = `` var editid = user._id edit += `添加用户
Document ` 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 增删改查(原始)
标签:nod upd number ima cti pre app 对象 div
原文地址:https://www.cnblogs.com/Rivend/p/12334103.html
评论
亲,登录后才可以留言!