student.js
var express = require('express'); var router = express.Router(); const _=require("lodash"); const { MongoClient } = require("mongodb"); //依赖MongoClient var client=new MongoClient("mongodb://127.0.0.1:27017"); //实例化一个客户端 var clientAdd=new MongoClient("mongodb://127.0.0.1:27017"); //实例化一个客户端 var clientdel=new MongoClient("mongodb://127.0.0.1:27017"); //实例化一个客户端 var books=[]; //查询全部 async function run(){ try{ let db=await client.db("BookMessge"); //获取数据库 let students=await db.collection("books"); //获取集合 let cursor=await students.find(); //执行查询并返回游标对象 await cursor.forEach(data=>books.push(data)); //遍历游标,取出数据 } finally{ await client.close(); //关闭 } }; //添加 async function add(booklist){ try{ let db=await clientAdd.db("BookMessge"); //获取数据库 let students=await db.collection("books"); //获取集合,表 let result=await students.insertOne(booklist); //执行向数据库中添加数据并等待响应结果 console.log(result); } finally{ await clientAdd.close(); //关闭数据库 } } //删除 async function del(id){ try{ let db=await clientdel.db("BookMessge"); //获取数据库 let students=await db.collection("books"); //获取集合,表 let result= await students.deleteOne(id); //执行删除 console.log(result); } finally{ await clientdel.close(); //关闭 } } run().catch(console.log); /* GET home page. */ router.get('/', function(req, res, next) { res.render('student', {books,msg: '',stu:{id:"",name:"",age:""}}); }); router.get('/delete/:id', function(req, res, next) { //查找选中id的索引 let id=req.params.id; console.log(id); let ids={id:""}; ids.id=id; console.log(ids); del(ids).catch(console.log); res.render('student', {books,msg: '删除成功!',stu:{id:"",name:"",age:""}}); }); //添加 router.post('/add', function(req, res, next) { //查找选中id的索引 let book=req.body; //根据编号排序 let new_id=_.orderBy(books,parseInt(["id"])); book.id=_.last(new_id).id+1; //拿到序号 let newbooks_id=_.orderBy(books,parseInt(["books_id"])); book.books_id=_.last(newbooks_id).books_id+1; console.log(book); add(book).catch(console.log); res.render('student', {books,msg: '添加成功'}); }); //修改 router.get('/edit/:id', function(req, res, next) { //查找选中id的索引 let stu=_.find(stus,{id:parseInt(req.params.id)}) console.log(stus); res.render('student', {stus,msg: '',stu}); }); //更新 router.post('/update', function(req, res, next) { //查找选中id的索引 let stuSubmit=req.body; let stu=_.find(stus,{id:parseInt(stuSubmit.id)}) stu.name=stuSubmit.name; stu.age=stuSubmit.age; //重新渲染页面 res.render('student', {stus,msg: '更新成功',stu:{id:"",name:"",age:""}}); }); module.exports = router;
student.ejs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>图书管理系统</title> </head> <body> <h1>图书管理系统</h1> <table width="100%" border="1"> <tr> <th>序号</th> <th>编号</th> <th>书名</th> <th>封面</th> <th>价格</th> <th>作者</th> <th>操作</th> </tr> <% for(let i=0;i<books.length;i++){ %> <tr style="text-align: center;"> <td><%=books[i].id%></td> <td><%=books[i].books_id%></td> <td><%=books[i].name%></td> <td><%=books[i].img%></td> <td><%=books[i].price%></td> <td><%=books[i].author%></td> <td> <a href="/delete/<%=books[i].id%>" class="del">删除</a> <a href="/edit/<%=books[i].id%>">修改</a> </td> </tr> <%} %> </table> <fieldset> <legend>添加学生</legend> <form method="post"> <input type="hidden" name="id" id="id" value="<%=books.id%>"> <input type="hidden" name="books_id" id="books_id" value="<%=books.books_id%>"> <p> <label>图书名称:</label> <input type="text" name="name" value="<%=books.name%>"> </p> <p> <label>图书封面:</label> <input type="file" name="img" value="<%=books.img%>"> </p> <p> <label>图书价格:</label> <input type="text" name="price" value="<%=books.price%>"> </p> <p> <label>图书作者:</label> <input type="text" name="author" value="<%=books.author%>"> </p> <button formaction="/add">添加</button> <button formaction="/update">更新</button> </form> </fieldset> <h4><%=msg%></h4> <script> let dels=document.querySelectorAll(".del"); for(let i=0;i<dels.length;i++){ dels[i].onclick=function(){ return confirm("您确定要删除吗?"); } } </script> </body> </html>
app.js
var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-parser'); var logger = require('morgan'); var indexRouter = require('./routes/index'); var usersRouter = require('./routes/users'); var studentRouter = require('./routes/student'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/index', indexRouter); app.use('/users', usersRouter); app.use('/', studentRouter); // catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app;
标签:Node,MongoDB,app,js,books,let,res,var,id From: https://www.cnblogs.com/zsbb/p/16714368.html