学生管理系统
let express = require('express'); let app = new express(); let MongoClient = require('mongodb').MongoClient; let bodyParser = require('body-parser'); var ObjectID = require("mongodb").ObjectID; //mongo数据库特有的ID app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // 依赖项 app.set('view engine','ejs'); // 查询数据 app.get('/',(req,res)=>{ res.redirect('/show') }) app.get('/show',(req,res)=>{ let URL = 'mongodb://127.0.0.1:27017/stuManger'; MongoClient.connect(URL,(err,db)=>{ if(err){ res.send('数据库链接失败'); return; } let collection = db.collection('stu'); collection.find().toArray((err,data)=>{ if(!err){ res.render('showStuinfo',{list:data}) } }) db.close(); }); }) // 添加数据 app.get('/add',(req,res)=>{ res.render('add'); }) app.post('/addDo',(req,res)=>{ let URL = 'mongodb://127.0.0.1:27017/stuManger'; MongoClient.connect(URL,(err,db)=>{ if(err){ res.send('数据库链接失败'); return; }; let collection = db.collection('stu'); let stumsg = { 'sname':req.body.sname, 'age':req.body.age, 'address':req.body.address, 'tel':req.body.tel, }; collection.insert(stumsg,(err,result)=>{ res.send('<script>alert("添加成功");location.href="/show"</script>'); }); db.close(); }); }); // 删除数据 app.get('/delete',(req,res)=>{ let URL = 'mongodb://127.0.0.1:27017/stuManger'; MongoClient.connect(URL,(err,db)=>{ if(err){ res.send('数据库链接失败'); return; } let collection = db.collection('stu'); let id = req.query.id; collection.remove({'_id':new ObjectID(id)},(err,data)=>{ res.send('<script>alert("删除成功");location.href="/show"</script>'); }) db.close(); }); }); // 修改数据 app.get('/updata',(req,res)=>{ let URL = 'mongodb://127.0.0.1:27017/stuManger'; MongoClient.connect(URL,(err,db)=>{ if(err){ res.send('数据库链接失败'); return; } let collection = db.collection('stu'); let id = req.query.id; collection.find({'_id':new ObjectID(id)}).toArray((err,data)=>{ res.render('updata',{single:data[0]}); }) db.close(); }); }); // 修改数据 app.post('/updataDo',(req,res)=>{ let URL = 'mongodb://127.0.0.1:27017/stuManger'; MongoClient.connect(URL,(err,db)=>{ if(err){ res.send('数据库链接失败'); return; } let collection = db.collection('stu'); let body = req.body; collection.update({'_id':new ObjectID(body.id)},{$set:{'sname':body.sname,'age':body.age,'address':body.address,'tel':body.tel}},(err,data)=>{ res.send('<script>alert("修改成功");location.href="/show"</script>'); }) db.close(); }); }); app.use((req,res)=>{ res.status(404).send('not Found 404'); }); app.listen(3000,()=>{ console.log('start'); })